【问题标题】:Get the max array from an array multidimensional based on value of column根据列的值从多维数组中获取最大数组
【发布时间】:2015-11-30 11:41:52
【问题描述】:

我有这个数组调用$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']);,但没有用。你能帮帮我吗?

【问题讨论】:

  • 如果有 2 个 key 包含 max return both?

标签: php arrays multidimensional-array php-5.3


【解决方案1】:

您可以将uasort 与current 一起使用,如 as

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

print_r(current($arr));

您可以像 as 一样简单地使用usort

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

print_r($arr[0]);

Demo

【讨论】:

  • 对current的恶意使用!
  • 但你是那些为答案发表评论的用户之一,我很感激
  • 我还是更喜欢使用current的那个:)
【解决方案2】:

试试这个

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

print_r(current($array));

【讨论】:

    【解决方案3】:

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

    $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
    

    【讨论】:

      猜你喜欢
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 2015-04-22
      • 2021-07-30
      相关资源
      最近更新 更多