将多维数组与值的总和合并 [英] merge multidimensional array with sum of values

查看:50
本文介绍了将多维数组与值的总和合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个看起来像这样的多维数组:

So i have an multidimensional array that looks like this:

Array
(
    [0] => Array
    (
        [GB] => 20827
        [US] => 73
        [ES] => 23
        [AU] => 15
        [DE] => 12
        [MY] => 4
        [QA] => 1
        [VN] => 1
        [SK] => 1
        [FJ] => 1
        [ME] => 1
        [TR] => 1
        [LV] => 1
    )

    [1] => Array
    (
        [GB] => 15070
        [US] => 3920
        [IE] => 1711
        [PH] => 1071
        [MT] => 578
        [AU] => 423
        [HR] => 241
        [ZA] => 210
        [FR] => 139
    )

)

我想用多维数组的每个数组中的所有键以及值的总和来创建一个新数组.

I want to create a new array with all of the keys in each array of the multidimensional array along with the sum of values.

这是我想要的结果,总计为总和:

This is the result i am aiming for, TOTAL been the sum:

Array
(
    [GB] => TOTAL
    [US] => TOTAL
    [ES] => TOTAL
    [AU] => TOTAL
    [DE] => TOTAL
    [MY] => TOTAL
    [QA] => TOTAL
    [VN] => TOTAL
    [SK] => TOTAL
    [FJ] => TOTAL
    [ME] => TOTAL
    [TR] => TOTAL
    [LV] => TOTAL
    [IE] => TOTAL
    [PH] => TOTAL
    [MT] => TOTAL
    [HR] => TOTAL
    [ZA] => TOTAL
    [FR] => TOTAL
)

推荐答案

浏览每个子数组,然后遍历键/值对.将它们添加到 $ final 数组中:

Look through each of the sub-arrays, and then loop through the key/value pairs. Add them up in a $final array:

$final = [];
foreach($masterArray as $subArray) {
    foreach($subArray AS $key => $value) {
        $final[$key] = isset($final[$key])
            ? $final[$key] + $value
            : $value;
    }
}

工作示例: https://3v4l.org/6XBbD

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

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