微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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
        )

)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐