Search code examples
phpphp-5.3

Find & track max value in a multidimensial array


I have a multidimensional array that looks like this:

Array
(
[0] => Array
    (
        [id] => 2280764150
        [label] => Some Label A
        [pda] => 5.34
        [prt] => 67
        [kps] => 12436
        [xmv] =>  1.24
    )

[1] => Array
    (
        [id] => 2273499083
        [label] => Some Label B
        [pda] => 2.99
        [prt] => 97
        [kps] => 212436
        [xmv] =>  7.78
    )

[2] => Array
    (
        [id] => 2273045947
        [label] => Some Label C
        [pda] => 6.34
        [prt] => 157
        [kps] => 1436
        [xmv] =>  2.34
    )

)

What I would like to do is find out which array element has the max value for each of items pda prt kps and xmv. It's not so much I want to know what the max value is, but I want to know which one has the max elements for each. So Some Label C would be logged as having max pda, Some Label B having max value for kps and so on.

I could do this with a few loops, but was looking for a more elegant solution.


Solution

  • Here's another one. I'm not sure if it's elegant, though.

    $arr = array(
        array('id'=>2280764150,'label'=>'Some Label A','pda'=>5.34,'prt'=>67,'kps'=>12436,'xmv'=>1.24),
        array('id'=>2273499083,'label'=>'Some Label B','pda'=>2.99,'prt'=>97,'kps'=>212436,'xmv'=>7.78),
        array('id'=>2273045947,'label'=>'Some Label C','pda'=>6.34,'prt'=>157,'kps'=>1436,'xmv'=>2.34),
    );
    
    $max = array('pda'=>0,'prt'=>0,'kps'=>0);
    foreach (array_keys($max) as $key) {
        array_walk($arr,'get_max',$key);
    }
    
    function get_max($inner_arr,$index,$key) {
        global $max;
        if ($inner_arr[$key] > $max[$key]['max'])
        $max[$key] = array('index'=>$index,'max'=>$inner_arr[$key]);
    }
    
    print_r($max);
    

    EDIT: ABOVE CODE SHORTENED

    $max = array('pda'=>0,'prt'=>0,'kps'=>0);
    array_walk($arr,'get_max');
    
    function get_max($inner_arr,$index) {
        global $max;
        foreach (array_keys($max) as $key) {
            if ($inner_arr[$key] > $max[$key]['max'])
            $max[$key] = array('index'=>$index,'max'=>$inner_arr[$key]);
        }
    }