Home > other >  Sum of multiple collection Laravel
Sum of multiple collection Laravel

Time:07-20

I wish to get the sum of multiple collection

$collection1 = collect([1, 2, 3]);
$collection2 = collect([4, 8, 1]);
$collection3 = collect([5, 7, 1]);

I wish the result like that

$collection = [10,17,5];

CodePudding user response:

if you can merge all collections in an array, this code help you:

$newColl = collect([0, 0, 0]);
foreach([$collection1, $collection2, $collection3] as $coll){
    for($i = 0; $i < $coll->count(); $i  ){
         $newColl[$i]  = $coll[$i];
    }
}

CodePudding user response:

$number_of_collections = x;
    for($i=1 ; $i<=$number_of_collections ; $i  ){
         $collection[$i] = $collection1[$i] $collection2[$i] $collection3[$i];
    }
  • Related