PHP 多维数组中的数组总和

2022-01-09 00:00:00 arrays multidimensional-array sum php

这里需要一些帮助来总结多维 php 数组中的数组

Need a little help here with summing up arrays inside a multi dimensional php array

例如多维数组

Array
(
    [0] => Array
        (
            [0] => 30
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 2
            [7] => 5
        )

    [1] => Array
        (
            [0] => 50
            [1] => 4
            [2] => 8
            [3] => 4
            [4] => 4
            [5] => 6
            [6] => 9
            [7] => 2
        )
)

我想要一个结果数组,它将像这样保存这两个数组的总和

I want to have a result array that will be holding sum of both these arrays like this

Array
(
    [0] => 80
    [1] => 9
    [2] => 14
    [3] => 11
    [4] => 12
    [5] => 15
    [6] => 11
    [7] => 7
)

任何帮助将不胜感激

谢谢!

推荐答案

这应该适用于您的示例中的数组($arr 是您示例中的数组,我没有'为了简单起见,这里没有定义它):

This should work for arrays like the one of your example ($arr is an array like the one in your example, I haven't defined it here for simplicity's sake):

$res = array();
foreach($arr as $value) {
    foreach($value as $key => $number) {
        (!isset($res[$key])) ?
            $res[$key] = $number :
            $res[$key] += $number;
    }
}

print_r($res);

相关文章