我有以下收藏:
array:2 [▼
0 => array:21 [▼
"id" => 1
"referrer" => "Kariane Muller DVM"
"path" => null
"tracking_code_id" => 30
"sales" => 2
"field_name" => "ssn"
"income" => 4.0
"fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
]
2 => array:21 [▼
"id" => 1
"referrer" => "Kariane Muller DVM"
"path" => null
"tracking_code_id" => 30
"sales" => 1
"field_name" => "income"
"income" => 1.0
"fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
]
出于可见性目的,我已将其转换为数组。
如何将此集合折叠为一个集合,但我想
sum
income
个密钥进入最终集合中的一个。
其他密钥应该包括在内吗?
答案 0 :(得分:0)
我会从减少开始。如果我理解正确,你基本上希望原始收藏完整,但收入要总结并反映在每个项目中。
$summedIncome = $collection->reduce(function ($carry, $item) {
$income = $carry->has('income') ? ($item->income + $carry->income) : $item->income;
$carry->push($item);
$carry->each->income = $income;
return $carry;
}, collect([]));