简体   繁体   中英

Get max value from each column of a 2-dimensional array

I have an array within an array, for example:

[ 
    [0, 20, 5], 
    [5, 0, 15], 
    [5, 10, 0]
]

I need to get the max number in each column.

  • The max of [0 , 5 , 5] is 5 , so that goes into the result array.
  • The max of [20, 0, 10] is 20 , so that goes into the result array.
  • The max of [5, 15, 0] is 15 , so that goes into the result array.

The final result array must contain [5, 20, 15] .

First, the array has to be transposed (flip the rows and columns):

function array_transpose($arr) {
   $map_args = array_merge(array(NULL), $arr);
   return call_user_func_array('array_map', $map_args);
}

(taken from Is there better way to transpose a PHP 2D array? - read that question for an explanation of how it works)

Then, you can map the max function on the new array:

$maxes = array_map('max', array_transpose($arr));

Example: http://codepad.org/3gPExrhO

Output [I think this is what you meant instead of (5, 15, 20) because you said index 1 should be max of (20, 0, 10)]:

Array
(
    [0] => 5
    [1] => 20
    [2] => 15
)

Without the splat operator, array_map() with max() will return the max value for each row. ( [20, 15, 10] )

With the splat operator to transpose the data structure, the max value for each column is returned.

Code: ( Demo )

$array = [ 
    [0, 20, 5], 
    [5, 0, 15], 
    [5, 10, 0]
];

var_export(
    array_map('max', ...$array)
);

Output:

array (
  0 => 5,
  1 => 20,
  2 => 15,
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM