Rezzo
Rezzo

Reputation: 47

Finding Highest Value in Associative Array

Is there a relatively easy way to find the highest values for each of the keys in my associative arrays?

Array(

    0 => Array(
        "avgtime"   => 19.75,
        "bounces"   => 3,
        "pageviews" => 14,
        "visitors"  => 4
    )

    1 => Array(
        "avgtime"   => 1.125,
        "bounces"   => 7,
        "pageviews" => 9,
        "visitors"  => 8
    )

    2 => Array(
        "avgtime"   => 111,
        "bounces"   => 18,
        "pageviews" => 32,
        "visitors"  => 20
    )

    3 => Array(
        "avgtime"   => 6.9375,
        "bounces"   => 14,
        "pageviews" => 18,
        "visitors"  => 10   
    )

    4 => Array(
        "avgtime"   => 191,
        "bounces"   => 11,
        "pageviews" => 57,
        "visitors"  => 24
    )
);

I want to create one array that holds the highest value for each key so the end result would be.

Array(

    "avgtime"   => 191,
    "bounces"   => 18,
    "pageviews" => 57,
    "visitors"  => 24
);

Upvotes: 1

Views: 1801

Answers (2)

Vahe Shadunts
Vahe Shadunts

Reputation: 1966

function maxRecursive(array $arr) {
    $maxArray = array();
    array_walk_recursive($arr, function($val, $key) use(&$maxArray){
        if( ( !$maxArray[$key] ) || $maxArray[$key] < $val ){
            $maxArray[$key] = $val;
        }
    });
    return $maxArray;
}

Upvotes: 0

Philipp
Philipp

Reputation: 15629

Iterate over the Array and store the max values for each key

$temp = array();
foreach ($data as $item) {
    foreach ($item as $key => $value) {
        $temp[$key] = max(
                isset($temp[$key]) ? $temp[$key] : $value,
                $value);
    }
}

Upvotes: 3

Related Questions