【问题标题】:How to group array by key in PHP Laravel Builder query如何在 PHP Laravel Builder 查询中按键对数组进行分组
【发布时间】:2021-09-05 14:10:24
【问题描述】:

我是新的 Laravel,我只想按键分组我的数组。这是我到目前为止所做的:

代码:

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

返回值:

[
   {
      "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"
   }
]

我只想要这样的东西:

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

我尝试 foreach 到 $vehicles 变量,但它说 Cannot use object of type stdClass as array 有没有办法实现这一点?提前致谢。祝你有美好的一天~

【问题讨论】:

    标签: php arrays laravel object query-builder


    【解决方案1】:

    考虑到您的代码,我会使用 Laravel Collections 来做类似的事情:

    $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();
    

    请注意,您得到的错误不是在 foreach 中迭代,而是因为您正在返回一个 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;
    

    回到你在 Laravel 中的问题,我建议你使用 dumpdd (dump and die) Laravel 的函数进行调试。

    $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]);
     
    

    【讨论】:

    • @jreloz,如果我的回答帮助您考虑投票并标记为正确的话。
    • 在 cmets 中包含更多相关问题,以便我可以编辑和改进我的答案。
    • 这太棒了!谢谢你的帮助。完美运行。
    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2020-06-04
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多