I am new Laravel and I just want to group my array by key. Here’s what I have done so far:
Code:
JavaScript
x
$vehicles = DB::select('call get_vehicles');
return $vehicles;
Return Value:
JavaScript
[
{
"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:
JavaScript
[
{
"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:
JavaScript
$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.
JavaScript
// (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.
JavaScript
$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]);