获取next()和prev()数组元素时未按预期工作


getting next() and prev() array elements not working as expected

我有一个数组,其中包含查询搜索的所有结果。

我的问题是,我需要从这个数组中选择一行,然后才能选择下一行和上一行。

这是我的代码

function getUserProf(array $data, $faceid)
{
    //make sure that all data is saved in an array
    $userprof = array();
    //makes the array with the info we need
    foreach ($data as $val)
        if ($val['faceid'] == $faceid){
            $userprof = array ("id" => $val["id"], "total" => $val["total"], "faceid" => $val["faceid"], "lname" => $val["lname"], "fname" => $val["fname"], "hand" => $val["hand"], "shot1" => $val["shot1"], "shot1" => $val["shot1"], "shot2" => $val["shot2"], "shot3" => $val["shot3"], "shot4" => $val["shot4"], "shot5" => $val["shot5"]);
        }
        $next = next($data);//to get the next profile
        $prev = prev($data);//to get the next profile
        $userprofinfo = array('userprof' => $userprof, 'next' => $next);//make a array with the profile and the next prof and the prev prof
    //we return an array with the info
    return $userprofinfo;
}

这在某种程度上起作用,但它没有给我正确的下一行和上一行?

您的问题是prev()移动数组指针-1,next()再次移动它+1,导致$next与调用prev()之前启动的当前行完全相同。

此外,在完整的foreach()运行之后,您将获得$prev$next,这将使数组指针留在数组的末尾。(所以你总是会得到最后一个元素)

试试这个:

function getUserProf(array $data, $faceid) {
    foreach ($data as $key => $val) {
        if ($val['faceid'] == $faceid) {
            return array( 
                'userprof' => $val,
                'prev'     => isset($data[$key-1]) ? $data[$key-1] : array(),
                'next'     => isset($data[$key+1]) ? $data[$key+1] : array()
            );
        }
    }
}