Search code examples
phparraysmaxfilteringgrouping

Group rows of data by one column and find max value in another column within each group


I have following array:

$array = [
    [2000, 401],
    [2000, 317],
    [2000, 301],
    [2002, 285],
    [2002, 277],
    [2002, 271],
    [2001, 208],
    [2001, 263],
    [2002, 285],
    [2001, 262],
    [2000, 258]
]

Then I wrote following code to group its values:

$result06 = array();
foreach ($chart06 as $el) {
    if (!array_key_exists($el[0], $result06)) {
        $result06[$el[0]] = array();
    }
    $result06[$el[0]][] = $el[1];
}

With that we receive following result:

Array
(
[2000] => Array
    (
        [0] => 401
        [1] => 317
        [2] => 301
        [3] => 258
    )

[2002] => Array
    (
        [0] => 285
        [1] => 277
        [2] => 271
    )

[2001] => Array
    (
        [0] => 208
        [1] => 263
        [2] => 262
    )
)

Now how can I determine the max value of each subarray and transform it in a "flat" array just like the following?

Array
(
[2000] => 401
[2002] => 285
[2001] => 263
)

I tried this:

foreach ($result06 as $value){
    $resultMax[] = max($value);
}

but with that the result is:

Array
(
[0] => 401
[1] => 285
[2] => 263
)

But I really need the original keys being the same.


Solution

  • You can get the key in the foreach loop like this:

    foreach ($result06 as $key => $value){
        $resultMax[$key] = max($value);
    }