PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php $source = [ ["user_id" => 1, "item_id" => 991, "quantity" => 100], ["user_id" => 1, "item_id" => 992, "quantity" => 50], ["user_id" => 1, "item_id" => 993, "quantity" => 300], ["user_id" => 1, "item_id" => 992, "quantity" => 150], ["user_id" => 2, "item_id" => 991, "quantity" => 75], ["user_id" => 2, "item_id" => 992, "quantity" => 20], ["user_id" => 3, "item_id" => 991, "quantity" => 200], ["user_id" => 3, "item_id" => 992, "quantity" => 425], ["user_id" => 3, "item_id" => 991, "quantity" => 100], ["user_id" => 3, "item_id" => 992, "quantity" => 75] ]; $res = array_reduce ( $source, function($res, $el) { if (isset($res[$el['user_id'].$el['item_id']])) { $res[$el['user_id'].$el['item_id']]['quantity'] += $el['quantity']; } else { $res[$el['user_id'].$el['item_id']] = $el; } return $res; }, [] ); print_r(array_values($res));
Show:  
Copy Clear