2014-01-17 71 views
1

我已經包含產品項的數組,在某些情況下,該產品被添加到購物車兩次,我想刪除重複並添加量一起卸下從購物項目陣列重複,且增加量

該項目需要匹配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 
      ) 

    ) 
+0

我的答案以下幫助嗎? – jszobody

+0

它的確如此。感謝一束,芽。 – Ben

回答

2

像這樣(未經):

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

注意你的新陣列將通過項目索引ID,這實際上會幫助你很多。首先做到這一點,檢查現有的購物車項目比首先允許重複項目更容易。

如果你真的不喜歡$cleanArray通過ID索引,您可以在重複的清理後,擺脫那些:

$cleanArray = array_values($cleanArray); 
0

創建一個新的陣列檢查和合並結果:

$ check = array();

然後遍歷您的現有數組,並使用ID作爲您的檢查數組的數組鍵;


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

現在您應該有一個數組$ check來將原始數組替換爲組合結果。

哦看起來像jszobody打我吧:)