PHPize Online / SQLize Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy
Copy Format Clear
<?php $input = [ Array ( 'product_id' => 353534543, 'offer_id' => 23424234, 'stock' => 50, 'warehouse_id' => 31558867618000 ), Array ( 'product_id' => 353534543, 'offer_id' => 23424234, 'stock' => 12, 'warehouse_id' => 31558867618000 ), Array ( 'product_id' => 123456, 'offer_id' => 3333333, 'stock' => 6, 'warehouse_id' => 21558867618010 ), Array ( 'product_id' => 123456, 'offer_id' => 3333333, 'stock' => 6, 'warehouse_id' => 21558867618010 ), Array ( 'product_id' => 44444, 'offer_id' => 12314, 'stock' => 5, 'warehouse_id' => 21558867618010 ) ]; $output = array_reduce( $input, function($res, $el) { if(isset($res[$el['product_id'] . "_" . $el['offer_id']])){ $res[$el['product_id'] . "_" . $el['offer_id']]['stock']+=$el['stock']; } else { $res[$el['product_id'] . "_" . $el['offer_id']] = $el; } return $res; }, [] ); var_export(array_values($output));
Show:  
Copy