求教如何合并数组

WBOY
Release: 2016-06-23 14:15:08
Original
837 people have browsed it

//比如下面两个数组$a1=array(2=>array(1,2),3=>array(4));$a2=array(2=>array(5),5=>array(4));/***我想$a1跟$a2合并的结果为 array(2=>array(1,2,5),3=>array(4),5=>array(4));**/
Copy after login

有什么好的方法?


回复讨论(解决方案)

$keys = array_unique(array_keys(array_merge($arr1, $arr2)));foreach($keys as $k) { .....}
Copy after login

如果不考虑更进一步的递归 每次都是两个二维数组合并的话 直接写个循环然后array_merge如何?

楼上正解。。。

$a1 = array(2=>array(1,2),3=>array(4));$a2 = array(2=>array(5),5=>array(4));foreach($a2 as $k=>$v) {  if(isset($a1[$k])) $a1[$k] = array_merge($a1[$k], $v);  else $a1[$k] = $v;}print_r($a1);
Copy after login
Array
(
    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 5
        )

    [3] => Array
        (
            [0] => 4
        )

    [5] => Array
        (
            [0] => 4
        )

)

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template