从数组键php获取最大数字

时间:2012-07-26 21:03:06

标签: php arrays

我有这些数组,我需要做的是让每个数组分开检查[total]然后得到bigest 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做这些。请帮助!!

2 个答案:

答案 0 :(得分: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个,则最终会得到与输入数组中的元素数量相同的元素。

答案 1 :(得分: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));