假设我有几个具有相同结构的多维数组,如下所示:
$basketA['fruit']['apple'] = 1;
$basketA['fruit']['orange'] = 2;
$basketA['fruit']['banana'] = 3;
$basketA['drink']['soda'] = 4;
$basketA['drink']['milk'] = 5;
$basketB['fruit']['apple'] = 2;
$basketB['fruit']['orange'] = 2;
$basketB['fruit']['banana'] = 2;
$basketB['drink']['soda'] = 2;
$basketB['drink']['milk'] = 2
我需要一种方法来合并它们,所以我会得到这个:
$basketC['fruit']['apple'] = 3;
$basketC['fruit']['orange'] = 4;
$basketC['fruit']['banana'] = 5;
$basketC['drink']['soda'] = 6;
$basketC['drink']['milk'] = 7;
真正的多维数组会更复杂,这只是为了帮助解释我需要的东西.
谢谢!!!!
解决方法:
码
function readArray( $arr, $k, $default = 0 ) {
return isset( $arr[$k] ) ? $arr[$k] : $default ;
}
function merge( $arr1, $arr2 ) {
$result = array() ;
foreach( $arr1 as $k => $v ) {
if( is_numeric( $v ) ) {
$result[$k] = (int)$v + (int) readArray( $arr2, $k ) ;
} else {
$result[$k] = merge( $v, readArray($arr2, $k, array()) ) ;
}
}
return $result ;
}
测试
$basketA = array( "fruit" => array(), "drink" => array() ) ;
$basketA['fruit']['apple'] = 1;
$basketA['fruit']['orange'] = 2;
$basketA['fruit']['banana'] = 3;
$basketA['drink']['soda'] = 4;
$basketA['drink']['milk'] = 5;
$basketB = array( "fruit" => array(), "drink" => array() ) ;
$basketB['fruit']['apple'] = 2;
$basketB['fruit']['orange'] = 2;
$basketB['fruit']['banana'] = 2;
$basketB['drink']['soda'] = 2;
$basketB['drink']['milk'] = 2;
$basketC = merge( $basketA, $basketB ) ;
print_r( $basketC ) ;
产量
Array
(
[fruit] => Array
(
[apple] => 3
[orange] => 4
[banana] => 5
)
[drink] => Array
(
[soda] => 6
[milk] => 7
)
)