PHP 对具有相同键的数组值求和

PHP sum array values with same keys

这是原来的主数组:

数组 (

[0] => Array

    (
        [subtotal] => 0.6000
        [taxes] => 0.0720
        [charged_amount] => 0.6720
        [total_discount] => 0.0000
        [provinceName] => BC
        [store_key] => 1
        [store_id] => 5834
        [categories] => Array
            (
                [2] => 0.6000
                [4] => 0
                [3] => 0
            )

    )

[1] => Array
    (
        [subtotal] => 29.8500
        [taxes] => 2.3270
        [charged_amount] => 20.2370
        [total_discount] => 11.9400
        [provinceName] => MB
        [store_key] => 9
        [store_id] => 1022
        [categories] => Array
            (
                [2] => 0
                [4] => 29.8500
                [3] => 0
            )

    )

[2] => Array
    (
        [subtotal] => 0.3000
        [taxes] => 0.0390
        [charged_amount] => 0.3390
        [total_discount] => 0.0000
        [provinceName] => NB
        [store_key] => 8
        [store_id] => 1013
        [categories] => Array
            (
                [2] => 0.3000
                [4] => 0
                [3] => 0
            )

    )

[3] => Array
    (
        [subtotal] => 24.3100
        [taxes] => 1.1830
        [charged_amount] => 10.2830
        [total_discount] => 15.2100
        [provinceName] => NL
        [store_key] => 4
        [store_id] => 3033
        [categories] => Array
            (
                [2] => 24.3100
                [4] => 0
                [3] => 0
            )

    )

[4] => Array
    (
        [subtotal] => 1116.3400
        [taxes] => 127.6960
        [charged_amount] => 1110.0060
        [total_discount] => 134.0300
        [provinceName] => ON
        [store_key] => 2
        [store_id] => 1139
        [categories] => Array
            (
                [2] => 85.7300
                [4] => 143.2800
                [3] => 887.3300
            )

    )

[5] => Array
    (
        [subtotal] => 10.8500
        [taxes] => 1.4100
        [charged_amount] => 12.2600
        [total_discount] => 0.0000
        [provinceName] => ON
        [store_key] => 5
        [store_id] => 1116
        [categories] => Array
            (
                [2] => 10.8500
                [4] => 0
                [3] => 0
            )

    )   

)

我只需要用相同的键添加数组 [categories] 的值并进一步使用它来打印总数,但没有得到正确的输出,有人可以帮我得到想要的结果吗:

想要的结果

具有相同键但单个数组值总和的数组

Array ( [2] => 0.9000 [4] => 29.8500 [3] => 1.5 ) 

注意:初始数组是动态的,可以有n个键值对

谢谢

您需要做的第一件事是遍历外部数组。然后,对于外部数组中的每一行,您将循环访问 category 元素中的每个条目。所以这意味着我们有两个 foreach 循环。在内部 foreach 中,我们只需将当前索引的值设置为 'sum' 数组中相同索引的值(如果它不存在),或者增加该索引的值(如果它已经存在)存在于 'sum' 数组中。

<?php
$sumArray = array();

foreach($outerArray as $row)
{
    foreach($row["categories"] as $index => $value)
    {
        $sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
    }
}
?>

Demo using your example array