php | Array merge

后端 未结 1 1337
星月不相逢
星月不相逢 2021-01-28 14:58

I have an array:

Array
(
    [0] => Array
        (
            [qty] => 2
            [id] => 1
            [name] => Name 1
            [sku] =>         


        
相关标签:
1条回答
  • 2021-01-28 15:15
    $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 讨论(0)
提交回复
热议问题