2012-07-28 3 views
0

배열에 쿼리 검색 결과가 있습니다.next() 및 prev() 배열 요소가 예상대로 작동하지 않습니다.

내 문제는이 배열에서 한 행을 선택하고 다음 및 이전 행을 선택할 수 있어야한다는 것입니다. 여기

이 어떻게 든 작동 내 코드

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

이지만, 그것은 나에게 올바른 다음 및 이전 행을 제공하지 않는 이유는 무엇입니까?

답변

2

귀하의 문제는 prev() 배열 포인터 -1 다시, 당신은 prev()를 호출하기 전에 시작 현재와 동일한 행되는 $next 결과 +1 next() 움직임을 이동한다는 것입니다.

또한 전체 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() 
      ); 
     } 
    } 
} 
+0

좋아하지만, 내가 어떻게이 $ 키 값을 키 입력합니까 ??? –

+0

@ YairVillar 더 나은 예제 – Kaii

+0

완벽한 사람을 위해 수정했습니다. 더 나은 성능을 위해 –

관련 문제