Home > Enterprise >  How to get sum of each type
How to get sum of each type

Time:03-11

I have a collection and would like to sum by type.

[
  ['type' => 0, 'amount' => 5],
  ['type' => 1, 'amount' => 5],
  ['type' => 0, 'amount' => 5]
]

What I want:

[
  ['type' => 0, 'amount' => 10],
  ['type' => 1, 'amount' => 5]
]

How can I achieve this in Laravel?

CodePudding user response:

Here you go:

 $yourCollectionSums = $yourCollection->groupBy('type')
   ->map(function ($row) {
     return $row->sum('amount');
   });
 
 $result = [];

 foreach($yourCollectionSums as $key => $sum){
    $result[$key] = ['type' => $key, 'sum' => $sum]
 }

 // $result will give you desired result.

CodePudding user response:

try the code will help you

$result[] = [];
    $collection = $collection->groupBy('type')
                             ->map(function ($row) {
                                 return $row->sum('amount');
                             })
                             ->map(function ($amount, $type) {
                                 $result['type'] = $type;
                                 $result['amount'] = $amount;

                                 return $result;
                             });
  • Related