从购物车项目数组中删除重复项并添加数量

时间:2014-01-17 18:41:43

标签: php arrays

我有一个包含产品项目的数组,在某些情况下,产品会被添加到购物车两次,我想删除重复项并将数量加在一起

这些项目需要与id

匹配

我能解决这个问题的最佳方法是什么?

示例数组是:

Array
        (

        [0] => Array
            (
                [type] => fabrication
                [id] => 886
                [price] => 11.00
                [quantity] => 1
                [producttitle] => Edge Profiles - Edge Profile B - Single 5mm Radius
                [index] => 2
            )

        [1] => Array
            (
                [type] => fabrication
                [id] => 887
                [price] => 11.00
                [quantity] => 1
                [producttitle] => Edge Profiles - Edge Profile C - Single 19mm Radius
                [index] => 3
            )

        [2] => Array
            (
                [type] => fabrication
                [id] => 887
                [price] => 11.00
                [quantity] => 10
                [producttitle] => Edge Profiles - Edge Profile C - Single 19mm Radius
                [index] => 4
            )

    )

这应该成为:

Array
    (

        [0] => Array
            (
                [type] => fabrication
                [id] => 886
                [price] => 11.00
                [quantity] => 1
                [producttitle] => Edge Profiles - Edge Profile B - Single 5mm Radius
                [index] => 2
            )

        [1] => Array
            (
                [type] => fabrication
                [id] => 887
                [price] => 11.00
                [quantity] => 11
                [producttitle] => Edge Profiles - Edge Profile C - Single 19mm Radius
                [index] => 3
            )

    )

2 个答案:

答案 0 :(得分:2)

像这样(未经测试):

$cleanArray = array();
foreach($array AS $item) {
    if($cleanArray[$item['id']]) {
        $cleanArray[$item['id']]['quantity'] += $item['quantity'];
    } else {
        $cleanArray[$item['id']] = $item;
    }
}

请注意,您的新数组将按项目ID编制索引,这实际上会帮助您解决很多问题。最初这样做,并且更容易检查现有的购物车项目,而不是首先允许重复。

如果您真的不喜欢通过ID索引$cleanArray,那么您可以在重复清理后删除那些:

$cleanArray = array_values($cleanArray);

答案 1 :(得分:0)

创建一个新数组来检查和组合结果:

$ check = array();

然后遍历现有数组并使用id作为check数组的数组键;


foreach(array as $whatever){  
  if(isset($check[$whatever['id']])){  
    $check[$whatever['id']]['quantity'] += $whatever['quantity'];  
  } else {  
    $check[$whatever['id']] = $whatever;  
  }  
}  

现在你应该有一个数组$ check来用原始数组替换结果。

哦,看起来像是jszobody打败了我:)