Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
)
like image 441
JSP64 Avatar asked Dec 08 '25 10:12

JSP64


1 Answers

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

Seems to do the trick rather nicely.

like image 170
Madara's Ghost Avatar answered Dec 10 '25 00:12

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!