Get the max array from an array multidimensional based on value of column

I have this array call $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
    )

)

Now I want to get the array who have the max number of column totalGames, in this case I want to get the array with the key 682. I tried like this $aMaxGame= max($aSumGame['totalGames']); but not work. Can you help me please ?

Answers


You can use uasort along with current function like as

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

print_r(current($arr));

You can simply use usort like as

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

print_r($arr[0]);

Demo


Try this

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

print_r(current($array));

Check this, haven`t ran it but should be ok:

$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

Need Your Help

Payara server not boot after a power failure

java java-ee glassfish payara

Payara server not boot after a power failure.

uploading an image through form

forms file-upload playframework image-uploading playframework-1.x

How should i write my controller class to upload an image through a form?