PHP数组合并?

时间:2012-12-27 08:38:52

标签: php

我有

Array_A ( [0] => Array ( [DATE] => 2012-11-28 , [totalCount] => )
          [1] => Array ( [DATE] => 2012-11-29 , [totalCount] => )
          [2] => Array ( [DATE] => 2012-11-30 , [totalCount] => ) )

Array_B ( [10] => Array ( [DATE] => 2012-11-28 , [totalCount] => 30 )
          [11] => Array ( [DATE] => 2012-11-30 , [totalCount] => 40 )
          [12] => Array ( [DATE] => 2012-12-05 , [totalCount] => 50 ) )

如果我需要将Array_A替换为Array_B中的值并且输出应为

,该怎么办?
Array_A ( [0] => Array ( [DATE] => 2012-11-28 , [totalCount] => 30 )
          [1] => Array ( [DATE] => 2012-11-29 , [totalCount] =>    )
          [2] => Array ( [DATE] => 2012-11-30 , [totalCount] => 40 ) )

2 个答案:

答案 0 :(得分:3)

我刚刚注意到你只需要使用来自array_a的键的部分,这个循环就可以了。

foreach($array_a as $key => $value){
    if (array_key_exists($key, $array_b){
        $result[$key] = $array_b[$key]; 
    } else {
        $result[$key] = null;
    }
}

或者,如果您希望在array_a中的密钥不存在时使用array_b的值,只需将else - 子句中的语句替换为:{{1} }。

答案 1 :(得分:2)

尝试

$result = array_merge_recursive($Array_A, $Array_B);
print_r($result);