2

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~

1 Answer 1

4

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]);
 
Sign up to request clarification or add additional context in comments.

2 Comments

@jreloz, if my answer helped you consider upvoting and also mark as the correct.
Include more related questions here in the comments so I can edit and improve my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.