我一直在获取集合中每一行的总和。
请参阅显示阵列的附图。
八月份:
"Aug-2022" => array:6 [▼
"annualbuffalomilksalerecordforcustomer" => "8.00"
"annuala2milksalerecordforcustomer" => "5.50"
"annualjerseymilksalerecordforcustomer" => "2.50"
"annualbuffalomilksalerecord" => "168.00"
"annuala2milksalerecord" => "0.00"
"annualjerseymilksalerecord" => "390.00"
我想计算所有值的总和 (574.00) 并将一个新元素附加到键为
sumofmilksale
的行。
预期结果:
"Aug-2022" => array:6 [▼
"annualbuffalomilksalerecordforcustomer" => "8.00"
"annuala2milksalerecordforcustomer" => "5.50"
"annualjerseymilksalerecordforcustomer" => "2.50"
"annualbuffalomilksalerecord" => "168.00"
"annuala2milksalerecord" => "0.00"
"annualjerseymilksalerecord" => "390.00"
"sumofmilksale" => "574.00"
map()
函数来做到这一点:
$collection = collect([
'Apr-2022' => [
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
],
'May-2022' => [
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
],
]);
$mapped = $collection->map(function ($entry) {
$sum = array_sum($entry);
return array_merge($entry, ['sumofmilksale' => $sum]);
})
dd($mapped);
肯尼建议的解决方案的更现代/优雅的风格是在
map()
方法调用中使用箭头函数语法和联合运算符。 (PHPize 演示)
$collection = collect([
"Jul-2022" => [],
"Aug-2022" => [
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
],
]);
var_export(
$collection->map(fn($row) => $row + ['sumofmilksale' => array_sum($row)])
);
输出:
\Illuminate\Support\Collection::__set_state(array(
'items' =>
array (
'Jul-2022' =>
array (
'sumofmilksale' => 0,
),
'Aug-2022' =>
array (
'annualbuffalomilksalerecordforcustomer' => '8.00',
'annuala2milksalerecordforcustomer' => '5.50',
'annualjerseymilksalerecordforcustomer' => '2.50',
'annualbuffalomilksalerecord' => '168.00',
'annuala2milksalerecord' => '0.00',
'annualjerseymilksalerecord' => '390.00',
'sumofmilksale' => 574.0,
),
),
'escapeWhenCastingToString' => false,
))
如果您的集合包含集合,您可以使用
put()
迭代调用 sum()
。 (PHPize 演示)
$collection = collect([
"Jul-2022" => collect([]),
"Aug-2022" => collect([
"annualbuffalomilksalerecordforcustomer" => "8.00",
"annuala2milksalerecordforcustomer" => "5.50",
"annualjerseymilksalerecordforcustomer" => "2.50",
"annualbuffalomilksalerecord" => "168.00",
"annuala2milksalerecord" => "0.00",
"annualjerseymilksalerecord" => "390.00",
]),
]);
var_export(
$collection->map(fn($coll) => $coll->put('sumofmilksale', $coll->sum()))
);