合并 2 个数组并对值求和(数字键) [英] Merge 2 Arrays and Sum the Values (Numeric Keys)
本文介绍了合并 2 个数组并对值求和(数字键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个数组
Array
(
[010156] => Array
(
[supp_number] => 010156
[totalamount] => 4.113,23
[debtorcred] => H
[amount1] => 4.113,23-
[amount2] =>
[amount3] =>
[amount4] =>
[amount5] =>
[amount6] =>
)
)
Array
(
[010156] => Array
(
[supp_number] => 010156
[totalamount] => 4.113,23
[debtorcred] => H
[amount1] => 4.113,23-
[amount2] =>
[amount3] =>
[amount4] =>
[amount5] =>
[amount6] =>
)
)
我是否可以将这些单独的数组合并为一个并将这些值加在一起,以便结果是:
Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:
Array
(
[010156] => Array
(
[supp_number] => <<<TOTAL >>>
[totalamount] => <<<TOTAL >>>
[debtorcred] => <<<TOTAL >>>
[amount1] => <<<TOTAL >>>
[amount2] => <<<TOTAL >>>
[amount3] => <<<TOTAL >>>
[amount4] => <<<TOTAL >>>
[amount5] => <<<TOTAL >>>
[amount6] => <<<TOTAL >>>
)
)
这是我目前拥有的功能,但我似乎无法使其工作:
This is the function I have at the moment but I cannot seem to make it work:
function array_merge_numeric_values()
{
$arrays = func_get_args();
$merged = array();
foreach ($arrays as $array)
{
foreach ($array as $key => $value)
{
if ( ! isset($merged[$key]))
{
$merged[$key] = $value;
}
else
{
$merged[$key] += $value;
}
}
}
推荐答案
这个实际的计算可以用2行代码完成,不需要循环:
This actual calculation can be done in 2 lines of code, no need for loops:
http://codepad.viper-7.com/ieSkHQ
$arr1 = array('amount1' => 1, 'amount2' => 6);
$arr2 = array('amount1' => 2, 'amount2' => 7);
$add = function($a, $b) { return $a + $b; };
$summedArray = array_map($add, $arr1, $arr2);
print_r($summedArray);
您只需根据嵌套结构进行适当调整即可.
Youl'll just need to make the appropriate adjustment to account for you nested structure.
这篇关于合并 2 个数组并对值求和(数字键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文