Group array php

Tags: , , ,



I have an array as follows and I need group type_id

array:11 [▼
  0 => {
    +"product_id": 521
    +"product_name": "Name product 1"
    +"type_id": 1
  }
  1 => {
    +"product_id": 521
    +"product_name": "Name product 1"
    +"type_id": 2
  }
  2 => {
    +"product_id": 521
    +"product_name": "Name product 1"
    +"type_id": 3
  }
  3 => {
    +"product_id": 526
    +"product_name": "Name product 2"
    +"type_id: 1
  }
  4 => {
    +"product_id": 526
    +"product_name": "Name product 2"
    +"type_id": 2
  }
]

I want to group the type_id into an array as follows:

array:2 [▼
  0 => {
    +"product_id": 521
    +"product_name": "Name product 1"
    +"type_id" : {
        0 => 1
        1 => 2
        2 => 3
    }
  }
  1 => {
    +"product_id": 526
    +"product_name": "Name product 2"
    +"type_id": {
        0 => 1
        1 => 2
    }
  }
]

I tried but couldn’t group type_id . Any help much appreciated! Thanks very much!

Answer

Change the array to collection, so that you can use collection method like groupBy, map, pluck, values

collect($array)->groupBy('product_id')->map(function($products) {
    $obj = clone $products->first();
    $obj->type_id = $products->pluck('type_id');
    return $obj;
})->values()->all();


Source: stackoverflow