2013-06-27 176 views
0

我有一個數組:php |陣列合併

Array 
(
    [0] => Array 
     (
      [qty] => 2 
      [id] => 1 
      [name] => Name 1 
      [sku] => Model 1 
      [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
      [price] => 209.00 
     ) 

    [1] => Array 
     (
      [qty] => 1 
      [id] => 1 
      [name] => Name 1 
      [sku] => Model 1 
      [options] => Color: <em>Black (+10$)</em>. Memory: <em>16GB</em>. 
      [price] => 110.00 
     ) 

    [2] => Array 
     (
      [qty] => 1 
      [id] => 3 
      [name] => Name 2 
      [sku] => Model 2 
      [options] => 
      [price] => 100.00 
     ) 
) 

第一步是要找到相同的ID。如果相同的id存在轉換數組。 是否有可能獲得輸出數組(如果id相同,則刪除一個並將qty添加到另一個)?

Array 
    (
     [0] => Array 
      (
       [qty] => 3 // 2+1 
       [id] => 1 
       [name] => Name 1 
       [sku] => Model 1 
       [options] => Color: <em>Black (+10$)</em>. Memory: <em>32GB (+99$)</em>. 
       [price] => 209.00 
      ) 

     [1] => Array 
      (
       [qty] => 1 
       [id] => 3 
       [name] => Name 2 
       [sku] => Model 2 
       [options] => 
       [price] => 100.00 
      ) 
    ) 

謝謝!

+1

那麼價格和選擇呢? –

+0

如果你不關心其他屬性,使用'foreach'循環應該很容易。你有什麼嘗試,有什麼問題? – Barmar

回答

1
$result = array(); 
foreach ($input as $subarray) { 
    $id = $subarray['id']; 
    if (isset($result[$id])) { // Same ID 
    $result[$id]['qty'] += $subarray['qty']; // Add quantities 
    } else { 
    $result[$id] = $subarray; // New ID, put in results 
    } 
} 
$result = array_values($result); // Convert from associative array to indexed 
+0

謝謝。合適的解決 – user889349