Red Red - 6 months ago 19
PHP Question

php array group

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?

If I
foreach
the above then I will get a duplicate one, how can I avoid that?

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

EDIT : EVERYTHING WORKS FINE : BUT IS THERE ANY WAY TO ACHIEVE THE SAME WITH ONE FOREACH ?

Answer

There is no native one, just use a loop.

$result = array();
foreach ($arr as $data) {
  $id = $data['id'];
  if (isset($result[$id])) {
     $result[$id][] = $data;
  } else {
     $result[$id] = array($data);
  }
}
Comments