Laravel 数组分组并合并每组
Laravel array group by and merge each group
我有这样一个数组,如何按date
分组并合并每组?
$input = [
[
'date' => '2018-09-25',
'foo' => 'value1',
],
[
'date' => '2018-09-25',
'bar' => 'value2'
],
[
'date' => '2018-09-26',
'baz' => 'value3'
]
];
最后变成了这样:
[
[
'date' => '2018-09-25'
'foo' => 'value1'
'bar' => 'value2'
],
[
'date' => '2018-09-26'
'baz' => 'value3'
]
]
您可以使用 laravel collection.
首先,您需要按 groupBy method, then map 每个组进行分组并合并每个子数组。
代码:
$result = collect($input)
->groupBy('date')
->map(function ($item) {
return array_merge(...$item->toArray());
});
您将获得此合集:
最后去掉keys(date),可以用values, and simply convert the collection to an array(toArray).
结束代码:
$result = collect($input)
->groupBy('date')
->map(function ($item) {
return array_merge(...$item->toArray());
})
->values()
->toArray();
我有这样一个数组,如何按date
分组并合并每组?
$input = [
[
'date' => '2018-09-25',
'foo' => 'value1',
],
[
'date' => '2018-09-25',
'bar' => 'value2'
],
[
'date' => '2018-09-26',
'baz' => 'value3'
]
];
最后变成了这样:
[
[
'date' => '2018-09-25'
'foo' => 'value1'
'bar' => 'value2'
],
[
'date' => '2018-09-26'
'baz' => 'value3'
]
]
您可以使用 laravel collection.
首先,您需要按 groupBy method, then map 每个组进行分组并合并每个子数组。
代码:
$result = collect($input)
->groupBy('date')
->map(function ($item) {
return array_merge(...$item->toArray());
});
您将获得此合集:
最后去掉keys(date),可以用values, and simply convert the collection to an array(toArray).
结束代码:
$result = collect($input)
->groupBy('date')
->map(function ($item) {
return array_merge(...$item->toArray());
})
->values()
->toArray();