merge multidimensional array with sum of values

那年仲夏 提交于 2019-12-25 08:57:43

问题


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
)

回答1:


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;
    }
}

Working example: https://3v4l.org/6XBbD




回答2:


perhaps something like

$array = count($array1) > count($array2) ? $array1 : $array2;
$otherArray = count($array1) > count($array2) ? $array2 : $array1;

array_walk($array, function(&$value, $key, $otherArray) {
    $value = $value + (isset($otherArray[$key]) ? $otherArray[$key] : 0);
}, $otherArray);


来源:https://stackoverflow.com/questions/35952317/merge-multidimensional-array-with-sum-of-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!