我有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;
}
}
}
答案 0 :(得分:5)
这个实际计算可以用两行代码完成,不需要循环:
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);
您只需进行适当的调整即可考虑嵌套结构。
答案 1 :(得分:0)
在第一个数组中创建一个新的数组和循环
$array1 = array('my_num' => 10, 'my_num2' => 20);
$array2 = array('my_num' => 15, 'my_num2' => 25);
$newArray = array();
foreach($array1 as $num => $one){
if(isset($array2[$num])){
$newArray[$num] = $one+$array2[$num];
} else {
$newArray[$num] = $one;
}
}
print_r($newarray);
答案 2 :(得分:0)
$value
是一个数组,而不是一个值。你可以试试这个:
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] = array();
}
foreach($value as $kk => $vv)
{
if ( ! isset($merged[$key][$kk]))
{
$merged[$key][$kk] = $vv;
}
else
{
$merged[$key][$kk] += $vv;
}
}
}
}
}