douba2705 2015-06-17 08:54
浏览 63
已采纳

在数组PHP中合并重复项[关闭]

I have an array generated daily that will have duplicate products in it.

[0] => Array
    (
        [product_id] => 85
        [name] => Widescreen Espresso v6.1
        [quantity] => 1
    )

[1] => Array
    (
        [product_id] => 85
        [name] => Widescreen Espresso v6.1
        [quantity] => 2
    )

[2] => Array
    (
        [product_id] => 114
        [name] => Panama Esmerelda Diamond Mountain
        [quantity] => 1
    )

I want to find duplicate products and total them up in an array that would look like this:

[0] => Array
    (
        [product_id] => 85
        [name] => Widescreen Espresso v6.1
        [quantity] => 3
    )

[1] => Array
    (
        [product_id] => 114
        [name] => Panama Esmerelda Diamond Mountain
        [quantity] => 1
    )

UPDATE:

I didn't want to remove the duplicates I want to merge duplicates so that the quantity of the product is added together. I managed to work a solution to it with the help of Meenesh Jain's answer below.

           $final_array = array();
           foreach($order_data as $item => $item_value) {
               $pid = $item_value['product_id'];
               if(!isset($final_array[$pid])) {
                 $final_array[$pid] = $item_value;
               } else {
                 $final_array[$pid]['quantity'] += $item_value['quantity'];
               }
            }
            print_r(array_values($final_array));
  • 写回答

3条回答 默认 最新

  • dpli36193 2015-06-17 09:15
    关注

    You can do it with mysqli

    OR

    you can apply a custom method on your array

     $temp_array = $new_array = array();
     foreach($array as $key => $arr_values){
       if(!in_array($arr_values['product_id'], $temp_array)){
             array_push($temp_array, $arr_values['product_id']);
             array_push($new_array,$array[$key]);
       } 
      } 
    

    // this code will do the trick

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现
  • ¥15 vscode的红色箭头爆红和has no default export报错
  • ¥15 关于#sql#的问题:#情况描述 在用vs对项目进行调试时,出现找不到网络路径,然后查看SQL配置工具,发现SQL服务显示远程调用过程失败(相关搜索:防火墙)
  • ¥15 eNSP中基于默认路由及浮动路由的公司与分部互联和校园网综合项目
  • ¥15 主要进行描述泥浆在管路不同区段泥浆的密度不相同,泥浆的密度有高有低,此时管路的摩阻分布需要怎么计算,(标签-matlab)
  • ¥40 通过编制程序计算圆管内层流充分发展对流换热,参数如图5-4,以及公式5-16所示,要求用表5-6对程序计算准确性进行验证