gpt4 book ai didi

php - 如何在 PHP Laravel Builder 查询中按键对数组进行分组

转载 作者:行者123 更新时间:2023-12-04 07:28:41 24 4
gpt4 key购买 nike

我是新的 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有没有办法实现这一目标?提前致谢。祝你有美好的一天~

最佳答案

考虑到你的代码,我会使用 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 中的问题,我建议您使用 dump 进行调试或 dd (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]);

关于php - 如何在 PHP Laravel Builder 查询中按键对数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68075807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com