Merges a two-dimensional array into a one-dimensional array.

Source: Internet
Author: User

We all know that PHP has the built-in array merging function array_merage ($ arr, $ arr1, $ arr2, $ arr3 ); then how to put a two-dimensional array such as array (Array ('A' => 1, 'B' => 2), array ('c' => 3, 'D' => 4) Merge to the following Array

Array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4); it seems that, PHP does not currently have such built-in functions, so I wrote two methods by myself for your reference only.

First, the method is a recursive method. The Code is as follows:

<?php$newarray=array();function changearray($arr){    foreach($arr as $key=>$val){        if(is_array($val)){            changearray($val);        }else{            global $newarray;            $newarray[$key]=$val;        }    }}$arr=array(array('c'=>'d',array('d'=>'t',array('l'=>'m'))),array('e'=>'f'),'g'=>'gg','k'=>'kk');changearray($arr);print_r($newarray);

Second, the method uses a small trick, borrowed call_user_func_array ($ array ). The Code is as follows:

<?php   function merge_array($array){    return call_user_func_array('array_merge',$array);  }    $arr=array(array('a'=>1,'b'=>2,'c'=>3),array(4,5,6));  print_r(merge_array($arr));


Merges a two-dimensional array into a one-dimensional array.

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.