The Problem
I have a multidimensional array similar to the one below. What I'm trying to achieve is a way to find and retrieve from the array the one with the highest "Total" value, now I know there's a function called max
but that doesn't work with a multidimensional array like this.
What I've thought about doing is creating a foreach loop and building a new array with only the totals, then using max
to find the max value, which would work, the only issue would then be retrieving the rest of the data which relates to that max value. I'm not sure that's the most efficient way either.
Any ideas?
Array ( [0] => Array ( [Key1] => Key1 [Total] => 13 ) [1] => Array ( [Key2] => Key2 [Total] => 117 ) [2] => Array ( [Key3] => Key3 [Total] => 39 ) )
In line 5, we use the amax() method to find the maximum value in the array. Then, we print the maximum value in line 6. From lines 8 to 12, we define a numpy 2D array. In lines 14 and 15, we use the amax() method to find the maximum across the row and column respectively.
The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.
The easiest way of understanding a multidimensional array is to acknowledge every array as a one dimensional array. i.e A 3 dimensional array is one dimensional array and every element in the one dimensional is a 2 dimensional array.
Just do a simple loop
and compare values or use array_reduce
$data = array_reduce($data, function ($a, $b) { return @$a['Total'] > $b['Total'] ? $a : $b ; }); print_r($data);
See Live Demo
Since PHP 5.5 you can use array_column to get an array of values for specific key, and max it.
max(array_column($array, 'Total'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With