0

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 ?

1
  • If there are 2 keys containing max return both? Commented Nov 30, 2015 at 11:43

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Wicked use of current!
But you're one of those user who commented for an answer and I appreciate that
I still prefer the one using current :)
0

Try this

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

print_r(current($array));

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.