Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group subarrays by a column value?

I have the following array

Array (     [0] => Array         (             [id] => 96             [shipping_no] => 212755-1             [part_no] => reterty             [description] => tyrfyt             [packaging_type] => PC         )      [1] => Array         (             [id] => 96             [shipping_no] => 212755-1             [part_no] => dftgtryh             [description] => dfhgfyh             [packaging_type] => PC         )      [2] => Array         (             [id] => 97             [shipping_no] => 212755-2             [part_no] => ZeoDark             [description] => s%c%s%c%s             [packaging_type] => PC         )  ) 

How can I group the array by id? Is there any native php functions are available to do this?

While this approach works, I want to do this using a foreach, since with the above I will get duplicate items, which I'm trying to avoid?

On the above example id have 2 items, so its need to be inside of the id

like image 216
Red Avatar asked Oct 03 '12 10:10

Red


People also ask

How do I group an array in Swift?

Before Swift 5, the most straightforward way is to loop through each device in the array and manually assign each element to its respective category. In Swift 5, Apple has introduced a generic dictionary initializer to help developers deal with this kind of situation with just 1 single line of code.


1 Answers

There is no native one, just use a loop.

$result = array(); foreach ($data as $element) {     $result[$element['id']][] = $element; } 
like image 161
xdazz Avatar answered Sep 28 '22 17:09

xdazz