我有10个集合(以下示例中使用了3个),需要按键合并,但需要对值求和。我的集合如下:
[
'key1' => ['value1' => 5, 'value2' => 3, 'value3' => 0],
'key2' => ['value1' => 1, 'value2' => 6, 'value3' => 2],
'key3' => ['value1' => 0, 'value2' => 0, 'value3' => 1],
]
[
'key1' => ['value1' => 3, 'value2' => 1, 'value3' => 7],
'key2' => ['value1' => 1, 'value2' => 3, 'value3' => 2],
'key3' => ['value1' => 1, 'value2' => 6, 'value3' => 1],
]
[
'key1' => ['value1' => 2, 'value2' => 3, 'value3' => 9],
'key2' => ['value1' => 3, 'value2' => 8, 'value3' => 3],
'key3' => ['value1' => 1, 'value2' => 0, 'value3' => 6],
]
我希望获得一个这样的集合,其结果看起来像这样:
[
'key1' => ['value1' => 10, 'value2' => 7, 'value3' => 16],
'key2' => ['value1' => 5, 'value2' => 17, 'value3' => 7],
'key3' => ['value1' => 2, 'value2' => 6, 'value3' => 8],
]
有没有我错过的内置Laravel Collection方法,或者最好的方法是什么?
编辑:(更多信息)值始终为数字。任何集合中都没有字符串值。
编辑2:一些人问我尝试了什么。我尝试了这个,它有效:
$merged = [];
foreach ($seeds as $seed) {
foreach ($seed as $location => $values) {
foreach ($values as $key => $value) {
$merged[$location][$key] = $value + ($merged[$location][$key] ?? 0);
}
}
}
我只是想知道是否有更简洁的方法来实现同样的功能,而不是使用3个foreach循环。