1

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

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

这是我的代码

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;
}

这以某种方式起作用,但它没有给我正确的下一行和上一行?

4

1 回答 1

2

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

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

试试这个:

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()
            );
        }
    }
}
于 2012-07-28T18:11:46.963 回答