In the normal project development we will use to let multidimensional arrays into one-dimensional arrays, but a lot of programmer will not convert it, there are some do not think of good algorithm and then after the chaos of eight bad operation to the way it is forced, but the program code to write the redundancy is very large, The time complexity of the program and the complexity of the space are very large. Here's how I do this and the code is straightforward.
Implementation method:
Ⅰ using recursive calls;
Ⅱ first defines a static array constant to hold the result;
Ⅲ loop the multidimensional array;
Ⅳ determines whether an array, if it is a recursive call method;
Ⅴ if not, put the result in a static array constant;
Ⅵ returns the result (static array constant).
Implementation code:
<?php/** * ======================================= * Created by Zhihua_w. * Author:zhihua_w * DATE:2016/11/28 0003 * Time: Morning 9:11 * project:php Development Tips * Power: Implement multidimensional arrays into one-dimensional arrays * ============= ========================== * * */** * multidimensional array into a one-dimensional array * @param array $array multidimensional array * @return array $result _array one-dimensional array */ function Array_multi2single ($array) {//First define a static array constant to hold the result static $result _array = Array (); Loops a multidimensional array of foreach ($array as $value) {//determines if it is an array, if it is a recursive call method if (Is_array ($value)) {A Rray_multi2single ($value); } else//If not, put the result in a static array constant $result _array [] = $value; }//return result (static array constant) return $result _array; } $arr = Array (' name ' = = ' A ', ' sex ' = ' m ', ' sort ' = + 5), a Rray (' name ' = ' C ', ' sex ' = ' m ', ' sort ' = + 8), array (' name ' =&G T ' g ', ' sex ' = ' m ', ' Sort ' = 3), array (' name ' = = ' e ', ' sex ' = ' w ', ' sort ' = + 6), Array (' name ' = ' B ', ' sex ' = ' w ', ' sort ' = 2); Print_r (Array_multi2single ($arr)); ?>
Print the result to convert the multidimensional array into a one-dimensional array:
Array ( [0] = a [1] = M [2] = 5 [3] = = C [4] = M [5] = 8 [6] = = G [7] = = M [8] = 3 [9] ~ = e [ten] = W [one] = 6 [] = b [] = W [+] = 2 )