1. 程式人生 > 實用技巧 >php 二維陣列去重合並將相同數量累加

php 二維陣列去重合並將相同數量累加

            $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
        )
 
)