phplaravelcollectionsgrouping

Merge and group collections by shared column


I have 3 collections of different objects. I need to aggregate these 3 collections into 1 according to the shared value (here shared value is id). I mean:

$names = {"id":1, "name":"John"};
$ages = {"id":1, "age":20};
$address = "{"id":1, "address":"222"};
//  ...more...

If I return return $names->merge($ages)->merge($address), it will show me like this:

[
  {"id":1, "name":"John"},
  {"id":1, "age":20},
  {"id":1, "address":"222"},
  {"id":2, "name":"Jim"},
  {"id":2, "age":30},
  {"id":2, "address":"333"},
]

I want to return me like this:

[
   {"id":1, "name":"John", "age":20 , "address":"222"},
   {"id":2, "name":"Jim", "age":30 , "address":"333"}
]

Solution

  • This is my solution:

    $items = [
      {"id":1, "name":"John"},
      {"id":1, "age":20},
      {"id":1, "address":"222"},
      {"id":2, "name":"Jim"},
      {"id":2, "age":30},
      {"id":2, "address":"333"},
    ];
    
    $items = collect($items)->groupBy('id');
    $result = [];
    foreach ($items as $values) {
      $temp = [];
      foreach ($values as $value) {
        $temp = array_merge($temp, $value);
      }
      $result[] = $temp;
    }
    
    dd($result);