[Solved] Sum array values of the same product


You can do this using groupBy and map functions of Laravel’s Collection:

$collection = new \Illuminate\Support\Collection($array);
$group = $collection->groupBy('product_id');
$resultArray = $group->map(function($item, $key) {
            return [
                'total_size' => $item->sum('comp_size'),
                'product_id' => $key,
            ];
        });

This will let you expand the code a bit easier in the future.

1

solved Sum array values of the same product