Search code examples
phparraysmaxminarray-map

Find min/max in a two dimensional array


I have an array with the following format:

Array
(
    [0] => Array
        (
            [DateTime] => "2013-05-22 14:21:01"
            [Price] => 102.01
        )
    [1] => Array
        (
            [DateTime] => "2013-05-23 15:55:01"
            [Price] => 52.60
        )
    [2] => Array
        (
            [DateTime] => "2013-05-25 14:23:01"
            [Price] => 452.25
        )
    ... etc
)

I need to discover the lowest and highest value of Price.

min only returns they key. I've also tried max(array_map("max", $data)) but that only returns 452.25.

Will I have to use a foreach and do it manually?


Solution

  • Here's one way to get the min and max values:

    $min = min(array_column($array, 'Price'));
    $max = max(array_column($array, 'Price'));
    

    To return the nested array for the min and max:

    $prices = array_column($array, 'Price');
    $min_array = $array[array_search(min($prices), $prices)];
    $max_array = $array[array_search(max($prices), $prices)];
    

    You could do each in one line since that looked like what you were trying to do:

    $min_array = $array[array_search(min($prices = array_column($array, 'Price')), $prices)];
    $max_array = $array[array_search(max($prices = array_column($array, 'Price')), $prices)];
    

    PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column().

    Using array_map() to get just the min and max:

    $min = min(array_map(function($a) { return $a['Price']; }, $array));
    $max = max(array_map(function($a) { return $a['Price']; }, $array));
    

    There's probably a good array_filter() or array_reduce() as well.