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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵