如何在 PHP Laravel Builder 查询中按键对数组进行分组
How to group array by key in PHP Laravel Builder query
我是新手 Laravel,我只想按键对我的数组进行分组。这是我到目前为止所做的:
代码:
$vehicles = DB::select('call get_vehicles');
return $vehicles;
Return 值:
[
{
"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
(转储和死亡)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]);
我是新手 Laravel,我只想按键对我的数组进行分组。这是我到目前为止所做的:
代码:
$vehicles = DB::select('call get_vehicles');
return $vehicles;
Return 值:
[
{
"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
(转储和死亡)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]);