php 求和两个数组的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15549045/
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 09:27:03  来源:igfitidea点击:

Best method for sum two arrays

phparrayssum

提问by Philipp

I have two arrays:

我有两个数组:

$a = array(10, 2, 5, 10, 0);
$b = array(1, 20, 11, 8, 3);

I need to sum up and get the result:

我需要总结并得到结果:

$c = array(11, 22, 16, 18, 3);

Any suggestions on how do this without "foreach"?

关于如何在没有“foreach”的情况下做到这一点的任何建议?

回答by Philipp

a simple approach could be

一个简单的方法可能是

$c = array_map(function () {
    return array_sum(func_get_args());
}, $a, $b);

print_r($c);

Or if you could use PHP5.6, you could also use variadic functions like this

或者如果你可以使用 PHP5.6,你也可以使用这样的可变参数函数

$c = array_map(function (...$arrays) {
    return array_sum($arrays);
}, $a, $b);

print_r($c);

Output

输出

Array
(
    [0] => 11
    [1] => 22
    [2] => 16
    [3] => 18
    [4] => 3
)

回答by Gautam3164

Try like

试试像

$c = array();
foreach (array_keys($a + $b) as $key) {
    $c[$key] = $a[$key] + $b[$key];
}

回答by user1997620

There's no way you can do that without the "foreach" as you asked for, you need to loop on both arrays to get the respective values.

如果没有您要求的“foreach”,您就无法做到这一点,您需要在两个数组上循环以获取相应的值。

A function using the foreach would be :

使用 foreach 的函数是:

function sum_arrays($array1, $array2) {
    $array = array();
    foreach($array1 as $index => $value) {
        $array[$index] = isset($array2[$index]) ? $array2[$index] + $value : $value;
    }
    return $array;
}

Now you just need to do :

现在你只需要做:

$c = sum_arrays($a, $b);

回答by Samuel Bolduc

$c = array();
for($i=0;$i<count($a);$i++) {
  $c[$i] = $a[$i]+$b[$i];
}