Search code examples
phparraysgroupingsub-array

Group 2d array data by one column and accumulate another column's values in subarrays


I have a PHP array that I'm trying to transform into a different format, the only way I can think to do it would be a lot longer than it seems like it should need.

Example data:

Array (
[0] => Array (
    [type] => a
    [value] => 1
    )
[1] => Array (
    [type] => a
    [value] => 2
    )
[2] => Array (
    [type] => a
    [value] => 3
    )
[3] => Array (
    [type] => b
    [value] => 1
    )
[4] => Array (
    [type] => b
    [value] => 4
    )
[5] => Array (
    [type] => f
    [value] => 2
    )
) 

Into:

Array (
'a' => Array(1,2,3),
'b' => Array(1,4),
'f' => Array(2)
)

Solution

  • foreach ($array as $element) 
        $newArray[$element["type"]][] = $element["value"];
    

    Seems to do the trick rather nicely.