我有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] => ) )
我是否可以将这些单独的数组合并为一个并将这些值相加,以便结果为:
Array ( [010156] => Array ( [supp_number] => <<<TOTAL >>> [totalamount] => <<<TOTAL >>> [debtorcred] => <<<TOTAL >>> [amount1] => <<<TOTAL >>> [amount2] => <<<TOTAL >>> [amount3] => <<<TOTAL >>> [amount4] => <<<TOTAL >>> [amount5] => <<<TOTAL >>> [amount6] => <<<TOTAL >>> ) )
这是我目前拥有的功能,但我似乎无法使其工作:
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; } } }
可以用两行代码完成此实际计算,而无需循环:
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);
您只需要进行适当的调整即可解决您的嵌套结构。