Home > Article > Backend Development > Simple implementation method of converting multi-dimensional array to one-dimensional array in PHP, _PHP tutorial
The example in this article describes the simple implementation method of converting a multi-dimensional array to a one-dimensional array in PHP. Share it with everyone for your reference, the details are as follows:
The PHP language itself does not have a function to convert a multi-dimensional array into a one-dimensional array, but we can write a PHP function ourselves to achieve the function of converting multi-dimensional arrays into one-dimensional arrays.
Using recursion, it is simple and crude. The entire function body implements this function in 9 lines of code. The PHP source code is as follows:
$multi = array( array( array( 'wo', 'shi' ), 'php' ), 'cheng', array( array( 'xu', 'yuan', ) ), '!' ); $multi = arrToOne($multi); print_r($multi); function arrToOne($multi) { $arr = array(); foreach ($multi as $key => $val) { if( is_array($val) ) { $arr = array_merge($arr, arrToOne($val)); } else { $arr[] = $val; } } return $arr; }
The effect after execution:
Array ( [0] => wo [1] => shi [2] => php [3] => cheng [4] => xu [5] => yuan [6] => ! )
I hope this article will be helpful to everyone in PHP programming.