PHP多维数组内的数组总和 [英] PHP Sum Of arrays inside a multidimensional array

查看:40
本文介绍了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);

这篇关于PHP多维数组内的数组总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆