1

クエリ検索のすべての結果を含む配列があります。

私の問題は、この配列から 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()、配列ポインタを -1next()移動し、再び +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 に答える