PHP使用相同的键求和数组值

时间:2016-06-23 18:07:23

标签: php arrays sum key

这是原始主阵列:

阵 (

[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个键值对

由于

1 个答案:

答案 0 :(得分:0)

您需要做的第一件事就是遍历外部数组。然后,对于外部数组中的每一行,您将遍历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