根据列的值从多维数组中获取max数组

时间:2015-11-30 11:41:52

标签: php arrays multidimensional-array php-5.3

我有这个数组调用$aSumGame

Array
(
[682] => Array
    (
        [nature] => 682
        [totalGames] => 3
        [category] => super
    )

[707] => Array
    (
        [nature] => 707
        [totalGames] => 2
        [category] => event
    )

[728] => Array
    (
        [nature] => 728
        [totalGames] => 2
        [category] => event
    )

)

现在我想获得列数totalGames的最大数量的数组,在这种情况下,我想要使用键682获取数组。我试过这样$aMaxGame= max($aSumGame['totalGames']);但不行。你能帮帮我吗?

3 个答案:

答案 0 :(得分:2)

您可以将uasortcurrent功能一起使用,如

uasort($arr,function($a,$b){
    return $b['totalGames'] - $a['totalGames'];
});

print_r(current($arr));

您可以像{/ p>一样使用usort

usort($arr,function($a,$b){
    return $b['totalGames'] - $a['totalGames'];
});

print_r($arr[0]);

Demo

答案 1 :(得分:0)

检查一下,没有运行但是应该没问题:

$array = array('682'=>array('nature'=>1,'totalGames'=>3), '707'=>array('nature'=>1,'totalGames'=>2));
$tempArray = array();
foreach($array as $id=>$array2) {
    $tempArray[$array2['totalGames']][] = $id;// store by the number of games, ex : array('2'=>array(707, 728), '3'=>array(682)
}
$maxKey = max(array_keys($tempArray)); //get the max, ex: 3
var_dump($tempArray[$maxKey]); //all id`s with max, ex: array(682)
list($oneResult) = $tempArray[$maxKey]; //get 682
var_dump($array[$oneResult]); //element from the initial array from key

答案 2 :(得分:0)

试试这个

usort($array, function($a, $b) {
    return strnatcasecmp($b['totalGames'], $a['totalGames']);
});

print_r(current($array));