Reputation: 195
I have an array with all the results of a query search.
My problem is that i need to select one row from this array, and then be able to select the next and previous row.
here is my code
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;
}
This works somehow, but it doesn't give me the correct next and previous row?
Upvotes: 1
Views: 783
Reputation: 20550
Your problem is that prev()
moves the array pointer -1 and next()
moves it +1 again, resulting in $next
being the exact same row as the current one where you started before invoking prev()
.
Also, you get $prev
and $next
after the complete foreach()
run, which leaves the array pointer at the end of the array. (so you will always get the last element)
Try this instead:
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()
);
}
}
}
Upvotes: 2