0

私はこれらの配列を持っています。私がする必要があるのは、各配列を個別に取得して[合計]をチェックし、最大の5つの数字を取得することです。頑張ってるけど頭が爆発しそうなので助けてください!!

Array ( 
[0] => Array ( [id] => 50 [faceid] => 1508653983 [fname] => Mario [lname] => Zelaya [email] => Email [handicap] => Handicap [province] => Province [country] => Country [gender] => male [hand] => [shot1] => Shot #1 [shot2] => Shot #2 [shot3] => Shot #3 [shot4] => Shot #4 [shot5] => Shot #5 [news] => 1 [total] => 0 )

[1] => Array ( [id] => 49 [faceid] => 1665349411 [fname] => Yair [lname] => Villar [email] => servidorv@gmail.com [handicap] => lefthanded [province] => Buenos Aires [country] => Argentina [gender] => male [hand] => RH [shot1] => 200 [shot2] => 98 [shot3] => 98 [shot4] => 98 [shot5] => 98 [news] => 1 [total] => 592 ) 

[2] => Array ( [id] => 48 [faceid] => 1665349411 [fname] => Yair [lname] => Villar [email] => servidorv@gmail.com [handicap] => lefthanded [province] => Buenos Aires [country] => Argentina [gender] => male [hand] => RH [shot1] => 500 [shot2] => 250 [shot3] => 80 [shot4] => 30 [shot5] => 20 [news] => 1 [total] => 88000 )

) 

phpでこれらを行うにはどうすればよいですか。助けてください!!

4

2 に答える 2

2

PHP の usort 関数を使用して配列をソートしてみてください。

function cmp($a, $b)
{
    if ($a['total'] == $b['total'])
        return 0;

    return ($a['total'] > $b['total']) ? -1 : 1;
}

usort($yourarray, "cmp");

if (count($yourarray) > 5)
    $sortedArray = array_slice($yourarray, 0, 5);
else
    $sortedArray = $yourarray;

最高スコアの 5 つの要素を持つ配列になります。入力配列の要素が 5 つ未満の場合、最終的には入力配列と同じ数の要素になります。

于 2012-07-26T21:26:04.927 に答える
1
function getTop5(array $data, $high2low = true)
{
    $total = array();

    foreach ($data as $val)
        $total[$val["id"]] = $val["total"];

    asort($total);
    return $high2low ? array_reverse($total) : $total;
}

$data = array(
        array("id" => 1, "total" => 25),
        array("id" => 2, "total" => 32),
        array("id" => 3, "total" => 21),
        array("id" => 4, "total" => 28)
        );

print_r(getTop5($data));
于 2012-07-26T21:36:58.313 に答える