PHP:合并/添加多维数组?

假设我有几个具有相同结构的多维数组,如下所示:

$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
        )

)

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...