Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find highest value in multidimensional array [duplicate]

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         ) ) 
like image 302
Karl Avatar asked Jun 27 '13 09:06

Karl


People also ask

How do you find the maximum value of a 2D array?

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.

How do you calculate multidimensional array?

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.

Can array have more than 2 dimensions?

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.


2 Answers

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

like image 34
Baba Avatar answered Sep 21 '22 23:09

Baba


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'))

like image 187
Astrus Avatar answered Sep 18 '22 23:09

Astrus