PHP根据foreach循环内的值求和数组值

时间:2018-03-07 18:51:13

标签: php foreach associative-array

嗨我有一个具有共同值的关联数组。我想根据不同的值对这些值和组进行求和。

我的数组如下。

Array
(
    [supercategory] => Food
    [subtotal] => 1152.50
    [discount] => 10.0000
    [orderdiscount] => 10.00
    [itemdiscount] => 0.00
    [Total] => 1142.50
    [Tax] => 80.06
    [taxinclusive] => 0.00
    [taxexclusive] => 80.06
    [gratuity] => 0.00
    [totalsale] => 1222.56
)
Array
(
     [supercategory] => Drinks
    [subtotal] => 1152.50
    [discount] => 10.0000
    [orderdiscount] => 10.00
    [itemdiscount] => 0.00
    [Total] => 1142.50
    [Tax] => 80.06
    [taxinclusive] => 0.00
    [taxexclusive] => 80.06
    [gratuity] => 0.00
    [totalsale] => 1222.56
)
Array
(
     [supercategory] => Food
    [subtotal] => 1152.50
    [discount] => 10.0000
    [orderdiscount] => 10.00
    [itemdiscount] => 0.00
    [Total] => 1142.50
    [Tax] => 80.06
    [taxinclusive] => 0.00
    [taxexclusive] => 80.06
    [gratuity] => 0.00
    [totalsale] => 1222.56
)
Array
(
     [supercategory] => Alcohols
    [subtotal] => 1152.50
    [discount] => 10.0000
    [orderdiscount] => 10.00
    [itemdiscount] => 0.00
    [Total] => 1142.50
    [Tax] => 80.06
    [taxinclusive] => 0.00
    [taxexclusive] => 80.06
    [gratuity] => 0.00
    [totalsale] => 1222.56
)

在遍历此数组时,我想在foreach循环中对数组值求和/同时基于键超类别,以便我可以将具有相同值的所有这些键的总和相加。 请帮帮我。

1 个答案:

答案 0 :(得分:0)

您不必担心上一个/下一个值会对数组进行分组。

只需迭代它并使用您想要分组的列作为结果数组中的键。

foreach ($your_array as $item) {
    $groups[$item['supercategory']][] = $item;
}

这基本上会为您的数组添加一个维度,其中所有项目都在各自的supercategory下分组。

拥有该结构后,可以轻松地对群组进行操作。这是一个如何生成我认为你想要获得的总和的例子。

foreach ($groups as $cat => $items) {
    $category_totals[$cat] = array_sum(array_column($items, 'totalsale'));
}