php 二維陣列去重合並將相同數量累加
阿新 • • 發佈:2020-09-09
$arr = array( array( 'user_id' => 100, 'goods_id' => 10, 'number' => 1, ), array( 'user_id' => 102, 'goods_id' => 10, 'number' => 1, ), array( 'user_id' => 102, 'goods_id' => 10, 'number' => 1, ), array( 'user_id' => 102, 'goods_id' => 10, 'number' => 1, ), ); $result = array(); foreach($arr as $val){ $key = $val['user_id'].'_'.$val['goods_id']; if(!isset($result[$key])){ $result[$key] = $val; }else{ $result[$key]['number'] += $val['number']; } } echo '<pre>'; print_r(array_values($result)); echo '</pre>';
Array ( [0] => Array ( [user_id] => 100 [goods_id] => 10 [number] => 1 ) [1] => Array ( [user_id] => 102 [goods_id] => 10 [number] => 3 ) )