arrays - Laravel 集合图的方法来展平多维
问题描述
我有这段代码,我想将集合重命名为不同的键和值。但是当我使用map
方法时,值返回到它们现有的值key
,我想删除使用 map 展平多维集合的键method
检索模型:
$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();
Laravel 文档: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],
]
*/
推荐阅读
- python - 提取字符或拆分列(dtype float64)
- c# - 实体框架核心 - 延迟加载不适用于 Getters
- python - 如何将json文件输出(子进程)加载到python中的变量中?
- javascript - 无法解决“TypeError:不是函数”错误
- php - 如何从选择列表中选择选项,然后根据数据库记录更改第二个选择列表?
- javascript - 我可以使用中间件代理从 localhost url 重定向或路由到另一个
- record - 为什么这个记录结构正在编译但给出运行时错误
- android - 如何在 Android PWA 中的 OAuth 之后重定向到我的应用程序?
- sql - 如果范围大于365天,如何比较同一组中的SQL日期范围并输出
- c++ - 使用 EXPECT_NEAR 时输出在声明的容差范围内时出错