Search code examples
phplaravelcollectionssummapping

Append element to each row of a Laravel collection to hold the sum of all values in the row


I am stuck at getting the sum of each row in a collection.

Please refer to the 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"

I want to calculate the sum of all values (574.00) and append a new element to the row with a key of sumofmilksale.

Expected result:

"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"

enter image description here


Solution

  • 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);