How to merge two arrays by summing the merged values(如何通过对合并的值求和来合并两个数组)
问题描述
可能重复:
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;
}
这篇关于如何通过对合并的值求和来合并两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过对合并的值求和来合并两个数组
基础教程推荐
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在多维数组中查找最大值 2021-01-01