拉拉维尔收集地图方法,以扁平化多维



我有这段代码,我想将集合重命名为不同的键和值。 但是当我使用map方法时,该值返回到它们现有的key并且我想删除键以使用mapmethod展平多维集合

检索模型:

$user = User::find(123)->orderByDesc('created_at')->get()->pluck('name', 'id');
$data = $user->map(function ($value, $key) {
return [
'id'   => $key,
'text' => $value,
];
});

预期成果:

$data = [
[
'id' => 3,
'text' => 'Shinka Nibutani',
], [
'id' => 2,
'text' => 'Kashiwagi Rein',
], [
'id' => 1,
'text' => 'Alice Zuberg',
],
]

实际结果:

$data = [
3 => [
'id' => 3,
'text' => 'Shinka Nibutani',
],
2 => [
'id' => 2,
'text' => 'Kashiwagi Rein',
],
3 => [
'id' => 1,
'text' => 'Alice Zuberg',
],
]

你只需要在最后添加 values((。像这样:

$data = $user->map(function ($value, $key) {
return [
'id'   => $key,
'text' => $value,
];
})->values();

拉拉维尔文档:https://laravel.com/docs/7.x/collections#method-values

值((

values 方法返回一个新集合,其中键重置为连续整数:

$collection = collect([
10 => ['product' => 'Desk', 'price' => 200],
11 => ['product' => 'Desk', 'price' => 200]
]);
$values = $collection->values();
$values->all();
/*
[
0 => ['product' => 'Desk', 'price' => 200],
1 => ['product' => 'Desk', 'price' => 200],
]
*/

最新更新