PHP将数组值一起添加

时间:2011-12-20 17:42:19

标签: php mysql database arrays json

我有一个格式为

的数组
Array
(
    [0] => Array
        (
            [platform] => 1
            [sales] => 244
            [total] => 245971.00
            [average] => 1008.08
        )

    [1] => Array
        (
            [platform] => 2
            [sales] => 273
            [total] => 280454.48
            [average] => 1027.31
        )

    [2] => Array
        (
            [platform] => 3
            [sales] => 290
            [total] => 273408.00
            [average] => 942.79
        )

)

和另一个数组

Array
(
    [0] => Array
        (
            [platform] => 1
            [sales] => 243
            [total] => 245231.00
            [average] => 1128.08
        )

    [1] => Array
        (
            [platform] => 2
            [sales] => 233
            [total] => 2804248
            [average] => 103.31
        )

    [2] => Array
        (
            [platform] => 3
            [sales] => 293
            [total] => 223408.00
            [average] => 942.29
        )

)

如何将这些数组添加到一起以创建添加的所有值的数组。

例如,来自包含平台11的第一个数组的[sales] => 244和包含平台1的秒数组中的[sales] => 243。我想将它们组合成一个数组[sales] => 487(244 + 243) )对于平台1。

提前致谢

2 个答案:

答案 0 :(得分:1)

假设两个阵列在各自的键之间具有精确的1:1匹配:

$new_arr = array();
foreach($arr1 as $main_key => $sub_arr) {
    foreach($sub_arr as $sub_key => $val) {
        $new_arr[$main_key][$sub_key] = $val + $arr2[$main_key][$sub_key];
    }
}

其中$ arr1和$ arr2是你的两个原始数组。

答案 1 :(得分:-1)

您还可以通过array_merge合并两个数组 http://php.net/manual/en/function.array-merge.php