How to merge arrays

Source: Internet
Author: User
How to merge arrays // for example, the following two arrays $ a1 = array (2 = & gt; array (1, 2), 3 = & gt; array (4 )); $ a2 = array (2 = & gt; array (5), 5 = & gt; array (4 )); /*** the result of merging $ a1 and $ a2 is & nbsp; array (2 = & gt; a. how to merge arrays?

// For example, the following two arrays
$ A1 = array (2 => array (1, 2), 3 => array (4 ));
$ A2 = array (2 => array (5), 5 => array (4 ));
/**
* The result of merging $ a1 and $ a2 is array (2 => array (1, 2, 5), 3 => array (4 ), 5 => array (4 ));
**/

Is there any good method? Share To: array (1, 2), 3 => array (4); $ a2 = array (2 => array (5), 5 => array (4 )); /*** me... 'data-pics = ''>
------ Solution --------------------

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


------ Solution --------------------
If we do not consider further recursion, every time we merge two-dimensional arrays, we can directly write a loop and then what about array_merge?
------ Solution --------------------
Upstairs...
------ Solution --------------------
$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);
Array
(
[2] => Array
(
[0] => 1
[1] => 2
[2] => 5
)

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

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

)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.