phplaravelconcatenationgroupingdelimited

Group rows of a 2d array by a column and concatenate another column within each group as a comma separated string


I have array like this :

[
   0: {name: "Judi", age: 15, hobby: "playing a game"},
   1: {name: "Judi", age: 15, hobby: "swimming"},
   2: {name: "Judi", age: 15, hobby: "playing a basketball"},
   3: {name: "Jedi", age: 14, hobby: "coding"},
   4: {name: "Jedi", age: 14, hobby: "reading"},
   5: {name: "Jedi", age: 14, hobby: "listen to the music"},
]

and I wanna make my data look like this :

[
   0: {name: "Judi", age: 15, hobby: "playing a game, swimming, playing a basketball"},
   0: {name: "Jedi", age: 14, hobby: "coding, reading, listen to the music"},
]

How to group my data like that?


Solution

  • If the 'name' field is the identifier you can accomplish this with a few Collection methods:

    collect($data)->groupBy('name')->map(function ($group) {
        return ['hobby' => $group->pluck('hobby')->join(', ')] + $group->first();
    })->values();
    

    This assumes your data is an array of arrays.

    Laravel 8.x Docs - Collections - Creating Collections collect

    Laravel 8.x Docs - Collections - Available Methods :