When performing some array processing operations, sometimes it is necessary to convert multi-dimensional arrays into one-dimensional arrays. This article will introduce some methods to convert two-dimensional arrays into one-dimensional arrays in php.
Method 1: Loop traversal
A simple method is to use a foreach loop to traverse the two-dimensional array and add its elements to a one-dimensional array.
function array2To1($arr2){ $arr1 = array(); foreach($arr2 as $v){ foreach($v as $v2){ $arr1[] = $v2; } } return $arr1; }
Usage example:
$arr2 = array(array(1,2),array(3,4),array(5,6)); $arr1 = array2To1($arr2); print_r($arr1); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
Method 2: Recursion
Another commonly used method is to use recursion to process multi-dimensional arrays and peel them layer by layer into one-dimensional arrays.
function array2To1($arr2){ $arr1 = array(); foreach($arr2 as $v){ if(is_array($v)){ $arr1 = array_merge($arr1,array2To1($v)); }else{ $arr1[] = $v; } } return $arr1; }
Usage example:
$arr2 = array(array(1,2),3,array(array(4,5),6),7); $arr1 = array2To1($arr2); print_r($arr1); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 )
Method 3: Use PHP built-in functions
PHP provides some built-in functions to process multi-dimensional arrays, including array_reduce(), array_merge_recursive() and call_user_func_array() etc.
function array2To1($arr2){ return call_user_func_array('array_merge_recursive', $arr2); }
Usage example:
$arr2 = array(array(1,2),array(3,4),array(5,6)); $arr1 = array2To1($arr2); print_r($arr1); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )
After actual testing, using method three is more time-consuming, so this method is not recommended when processing large arrays.
Summary:
Each method has its own advantages and disadvantages, and which method to choose ultimately depends on the specific needs and scenarios. I hope this article can be helpful to you. If you have a better method, please share it in the comment area.
The above is the detailed content of How to convert a two-dimensional array into a one-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!