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

 

posted @ 2020-09-09 16:00  没事就更  阅读(1231)  评论(0编辑  收藏  举报