如何通过对合并的值求和来合并两个数组

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

可能重复:
PHP:如何对相同键的数组

我正在寻找一个不替换值但添加它们的 array_merge() 函数.

I am looking for an array_merge() function that does NOT replace values, but ADDS them.

例如,这是我正在尝试的代码:

Example, this is the code I am trying:

    echo "<pre>"; 

    $a1 = array(
         "a" => 2
        ,"b" => 0
        ,"c" => 5
    );

    $a2 = array(
         "a" => 3
        ,"b" => 9
        ,"c" => 7
        ,"d" => 10
    );

    $a3 = array_merge($a1, $a2);
    print_r($a3); 

可悲的是,这会输出:

Array
(
    [a] => 3
    [b] => 9
    [c] => 7
    [d] => 10
)

然后我尝试了,而不是 array_merge,只是简单地将两个数组相加

I then tried, instead of array_merge, just simply adding the two arrays

$a3 = $a1 + $a2;

但这会输出

Array
(
    [a] => 2
    [b] => 0
    [c] => 5
    [d] => 10
)

我真正想要的是能够根据需要传递尽可能多的数组,然后得到它们的总和.所以在我的例子中,我希望输出是:

What I truly want is to be able to pass as many arrays as needed, and then get their sum. So in my example, I want the output to be:

Array
(
    [a] => 5
    [b] => 9
    [c] => 12
    [d] => 10
)

当然,我可以使用许多 foreach 等来构建一些功能,但我正在寻找更智能、更清洁的解决方案.感谢您的任何指点!

Of course I can schlepp and build some function with many foreach etc, but am looking or a smarter, cleaner solution. Thanks for any pointers!

推荐答案

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = (isset($a1[$key]) ? $a1[$key] : 0) + (isset($a2[$key]) ? $a2[$key] : 0);
}

您可以使用错误抑制运算符将其缩短为以下内容,但它应该被认为是丑陋的:

You could shorten this to the following using the error suppression operator, but it should be considered ugly:

$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
    $sums[$key] = @($a1[$key] + $a2[$key]);
}

或者,一些映射:

$keys = array_fill_keys(array_keys($a1 + $a2), 0);
$sums = array_map(function ($a1, $a2) { return $a1 + $a2; }, array_merge($keys, $a1), array_merge($keys, $a2));

或两种解决方案的组合:

Or sort of a combination of both solutions:

$sums = array_fill_keys(array_keys($a1 + $a2), 0);
array_walk($sums, function (&$value, $key, $arrs) { $value = @($arrs[0][$key] + $arrs[1][$key]); }, array($a1, $a2));

我认为这些足够简洁,可以在需要时在现场调整其中一个,但可以将其描述为一个接受无限数量的数组并对它们求和的函数:

I think these are concise enough to adapt one of them on the spot whenever needed, but to put it in terms of a function that accepts an unlimited number of arrays and sums them:

function array_sum_identical_keys() {
    $arrays = func_get_args();
    $keys = array_keys(array_reduce($arrays, function ($keys, $arr) { return $keys + $arr; }, array()));
    $sums = array();

    foreach ($keys as $key) {
        $sums[$key] = array_reduce($arrays, function ($sum, $arr) use ($key) { return $sum + @$arr[$key]; });
    }
    return $sums;
}

相关文章