我有一个数组,其中包含查询搜索的所有结果。
我的问题是我需要从这个数组中选择一行,然后才能选择下一行和上一行。
这是我的代码
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;
}
这种方式有点工作,但它没有给我正确的下一行和上一行?
答案 0 :(得分:2)
您的问题是prev()
移动数组指针-1并且next()
再次移动+1,导致$next
与您之前开始的当前行完全相同调用prev()
。
此外,在完成$prev
运行后,您将获得$next
和foreach()
,这会将数组指针留在数组的末尾。 (所以你总是得到最后一个元素)
请改为尝试:
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()
);
}
}
}