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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,