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 saysCannot use object of type stdClass as array
is there any way to achieve this? thanks in advance. Have a good day~
Answer
Solution:
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 usingdump
ordd
(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]);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: too few arguments to function laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.