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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6086267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:18:49  来源:igfitidea点击:

How to merge two arrays by summing the merged values

phparrayssum

提问by Erick

Possible Duplicate:
PHP: How to sum values of the array of the same key

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

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

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

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

Sadly, this outputs this:

可悲的是,这会输出:

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

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

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

$a3 = $a1 + $a2;

But this outputs

但这输出

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
)

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

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

回答by deceze

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

You couldshorten 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]);
}

Alternatively, some mapping:

或者,一些映射:

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

回答by Wesley Murch

My contribution:

我的贡献:

function array_merge_numeric_values()
{
    $arrays = func_get_args();
    $merged = array();
    foreach ($arrays as $array)
    {
        foreach ($array as $key => $value)
        {
            if ( ! is_numeric($value))
            {
                continue;
            }
            if ( ! isset($merged[$key]))
            {
                $merged[$key] = $value;
            }
            else
            {
                $merged[$key] += $value;
            }
        }
    }
    return $merged;
}

Pass as many arrays to it as you want. Feel free to add some more defense, ability to accept multidimensional arrays, or type checking.

根据需要将尽可能多的数组传递给它。随意添加更多防御、接受多维数组的能力或类型检查。

Demo: http://codepad.org/JG6zwAap

演示:http: //codepad.org/JG6zwAap

回答by Haim Evgi

its not so complicate do something like:

它并不那么复杂,请执行以下操作:

$a3 = $a1;

foreach($a2 as $k => $v) {
    if(array_key_exists($k, $a3)) {
       $a3[$k] += $v;
    } else {
       $a3[$k] = $v; 
    }
}

回答by Sanjeev Kumar Jha

You can use array_push function.I hope it will help you

你可以使用 array_push 函数,希望对你有帮助

foreach($a2 as $a2){
    array_push($a1, $a2);
    }

    print_r($a1);

Output:

Array
(
    [a] => 2
    [b] => 0
    [c] => 5
    [0] => 3
    [1] => 9
    [2] => 7
    [3] => 10
)

OR you can change your logic in key value with numbers.It works even it have same number as follows:

或者您可以使用数字更改键值中的逻辑。即使它具有相同的数字,它也可以工作,如下所示:

<?php
$beginning = array(1 => 'foo');
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

Output:

Array (
 [0] => foo
 [1] => bar
 )

Enjoy!!!!!!!!!!!!!!

享受!!!!!!!!!!!!!!