0

我有这些数组,我需要做的是让每个数组单独检查 [total],然后得到最大的 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 回答