我有两个数组如下: -
$m_aggregate = array(
'weighted' => array (40000,
30000,
90000,
0),
'unweighted' => array (3000,
2000,
6000,
0),
'weighted_sum' => 160000,
'unweighted_sum' => 11000
);
$f_aggregate = array(
'weighted' => array (7000,
5000,
9000,
0),
'unweighted' => array (500,
300,
600,
0),
'weighted_sum' => 21000,
'unweighted_sum' => 1400
);
并希望总结各个元素,以便我得到
$tot_aggregate = array(
'weighted' => array (47000,
35000,
99000,
0),
'unweighted' => array (3500,
2300,
6600,
0),
'weighted_sum' => 181000,
'unweighted_sum' => 12400
);
我尝试过使用
function sum($arr1, $arr2)
{
return($arr1+$arr2);
}
$tot_aggregate = array_map("sum", $m_aggregate, $f_aggregate);
print_r($tot_aggregate);
但这给了我weighted_sum和unweighted_sum,但没有给出数组中加权和未加权的数组。
有人可以帮忙吗? TIA 雅
答案 0 :(得分:0)
function sum($arr1, $arr2)
{
return is_array( $arr1) && is_array( $arr2)
? array_map("sum", $arr1, $arr2)
: ($arr1 + $arr2);
}
$tot_aggregate = sum($m_aggregate, $f_aggregate);
print_r($tot_aggregate);
输出
Array
(
[0] => Array
(
[0] => 47000
[1] => 35000
[2] => 99000
[3] => 0
)
[1] => Array
(
[0] => 3500
[1] => 2300
[2] => 6600
[3] => 0
)
[2] => 181000
[3] => 12400
)