I am self leaner and stuck at getting the sum of array which i am getting. Ref. attached image showing the array. for Month of Aug.
"Aug-2022" => array:6 [▼
"annualbuffalomilksalerecordforcustomer" => "8.00"
"annuala2milksalerecordforcustomer" => "5.50"
"annualjerseymilksalerecordforcustomer" => "2.50"
"annualbuffalomilksalerecord" => "168.00"
"annuala2milksalerecord" => "0.00"
"annualjerseymilksalerecord" => "390.00"
Here i want the sum all 6 which is = 574.00
expected result is -
"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"
CodePudding user response:
You could do it like this using the map()
function :
$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);