Skip to content
Advertisement

How to group array by key in PHP Laravel Builder query

I am new Laravel and I just want to group my array by key. Here’s what I have done so far:

Code:

$vehicles = DB::select('call get_vehicles');
return $vehicles;

Return Value:

[
   {
      "vhc_id":"001",
      "vhc_make":"Toyota",
      "vhc_model":"HiluxSR"
   },
   {
      "vhc_id":"001",
      "vhc_make":"Toyota",
      "vhc_model":"HiluxSR5"
   },
   {
      "vhc_id":"001",
      "vhc_make":"Toyota",
      "vhc_model":"Landcruiser"
   },
   {
      "vhc_id":"002",
      "vhc_make":"Ford",
      "vhc_model":"Ranger"
   },
   {
      "vhc_id":"002",
      "vhc_make":"Ford",
      "vhc_model":"Falcon"
   }
]

I just want something like this:

[
   {
      "vhc_id":"001",
      "vhc_make":"Toyota",
      "vhc_model":[
         "HiluxSR",
         "HiluxSR5",
         "Landcruiser"
       ]
   },
   {
      "vhc_id":"002",
      "vhc_make":"Ranger",
      "vhc_model": [
         "Ranger",
         "Falcon"
       ]
   },
]

I tried foreach to $vehicles variable but it says Cannot use object of type stdClass as array is there any way to achieve this? thanks in advance. Have a good day~

Advertisement

Answer

Considering you code, I would use Laravel Collections, to do something like that:

$vehicles = DB::select('call get_vehicles');

return collect($vehicles)
            ->groupBy('vhc_id')
            ->map(function ($group) {
                return [
                    'vhc_id' => $group[0]->vhc_id,
                    'vhc_make' => $group[0]->vhc_make,
                    'vhc_model' => $group->pluck('vhc_model')
                ];
            })
            ->values()
            ->all();

Notice, that the error you got its not about iterating in foreach it’s because you are returning a array of stdClass.

// (object) is used to cast the array to stdClass
$x = (object) ['a' => 1, 'b' => 2]; 

// you CAN'T do that
$x['a'];

// you SHOULD do that
$x->a;

Back to you problem in Laravel, I recommend you to debug using dump or dd (dump and die) Laravel’s functions.

$vehicles = DB::select('call get_vehicles');

// dd to see your first vehicle as stdClass
dd($vehicles[0]);

// dd same thing as array
dd((array) $vehicles[0]);
 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement