假设我有几个具有相同结构的多维数组,如下所示:
$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;
真正的多维数组会更复杂,这个只是为了帮助解释我需要什么。
谢谢!!!!
最佳答案
使用标准的 PHP 方法是不可能的,您应该编写自己的函数:
代码
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
)
)
关于PHP:合并/添加多维数组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2113263/