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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么