将二维数组行按一列分组,并对每组内的另一列求和[重复]

问题描述 投票:0回答:1

我有一个数组:

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 相同,则删除一个数组并将数量添加到另一个数组中)?

 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
            )
    )
php arrays multidimensional-array sum grouping
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.