<?php
$A = array(
'A'=>array('a'=>array(
'v1'=>1
'v2'=>2
'v3'=>3
),
'b'=>array(
'v1'=>1
'v2'=>2
'v3'=>3
)
),
'B'=>array('a'=>array(
'v1'=>1
'v2'=>2
'v3'=>3
),
'b'=>array(
'v1'=>1
'v2'=>2
'v3'=>3
)
),
...
);
=>$total= array('a'=>array(
'v1'=>2
'v2'=>4
'v3'=>6
),
'b'=>array(
'v1'=>2
'v2'=>4
'v3'=>6
?>
它工作,但不是一个通用的方式。
$total_av1 = $A['A']['a']['v1'] + $A['B']['a']['v1'];
$total_av2 = $A['A']['a']['v2'] + $A['B']['a']['v2'];
$total_av3 = $A['A']['a']['v3'] + $A['B']['a']['v3'];
$total_bv1 = $A['A']['b']['v1'] + $A['B']['b']['v1'];
$total_bv2 = $A['A']['b']['v2'] + $A['B']['b']['v2'];
$total_bv3 = $A['A']['b']['v3'] + $A['B']['b']['v3'];
$total = array(
"a"=>array($total_av1,$total_av2,$total_av3),
"b"=>array($total_bv1,$total_bv2,$total_bv3)
);
echo '<pre>';
print_r($A);
print_r($total);
echo '</pre>';
如果你想更花哨(或者真的讨厌 foreach
):
源数组:
$A = array(
'Z'=>array('d'=>array(
'v1'=>10,
'v2'=>20,
'v3'=>30
)
),
'A'=>array('a'=>array(
'v1'=>1,
'v2'=>2,
'v3'=>3
),
'b'=>array(
'v1'=>1,
'v2'=>2,
'v3'=>3
)
),
'B'=>array('a'=>array(
'v1'=>1,
'v2'=>2,
'v3'=>3
),
'b'=>array(
'v1'=>1,
'v2'=>2,
'v3'=>3
)
),
'C'=>array('a'=>array(
'v1'=>9,
'v2'=>8,
'v3'=>7
),
'b'=>array(
'v1'=>6,
'v2'=>5,
'v3'=>4
)
)
);
程序:
$total=array_reduce($A,function(&$r,$v){
array_walk($v,function($val,$key)use(&$r){
if(!isset($r[$key])) $r[$key]=array();
array_walk($val,function($vv,$vk)use(&$r,$key){
if(!isset($r[$key][$vk])) $r[$key][$vk]=0;
$r[$key][$vk]+=$vv;
});
});
return $r;
},array());
print_r($total);
输出:
Array
(
[d] => Array
(
[v1] => 10
[v2] => 20
[v3] => 30
)
[a] => Array
(
[v1] => 11
[v2] => 12
[v3] => 13
)
[b] => Array
(
[v1] => 8
[v2] => 9
[v3] => 10
)
)
注意,我特意添加了一个不规则的$A['Z']
来演示这个过程。
要求PHP>=5.3。现场演示
这几乎是一样的。
$a['v1'] = $A['A']['a']['v1'] + $A['B']['a']['v1'];
$a['v2'] = $A['A']['a']['v2'] + $A['B']['a']['v2'];
$a['v3'] = $A['A']['a']['v3'] + $A['B']['a']['v3'];
$b['v1'] = $A['A']['b']['v1'] + $A['B']['b']['v1'];
$b['v2'] = $A['A']['b']['v2'] + $A['B']['b']['v2'];
$b['v3'] = $A['A']['b']['v3'] + $A['B']['b']['v3'];
$total= array('a'=> $a, 'b'=> $b);
echo "Not so generic <pre>";
print_r($total);
echo "</pre>";
要使其泛型,需要嵌套一些正确使用键的循环。
for ($i = 1; $i < count($A['A']['a']) + 1; $i++) {
$total2['a']['v'.$i] = $A['A']['a']['v'.$i] + $A['B']['a']['v'.$i];
$total2['b']['v'.$i] = $A['A']['b']['v'.$i] + $A['B']['b']['v'.$i];
}
echo "Sort of generic <pre>";
print_r($total2);
echo "</pre>";