In normal project development, we often use the situation of converting multi-dimensional arrays into one-dimensional arrays. However, many Programmers do not convert them, and some do not think of a good algorithm and then go through a messy process. The calculation method can barely convert it well, but the written program code is very redundant, causing the program's time complexity and space complexity to be very large. Below I will describe how I achieved this situation, and the code is simple and clear.
Implementation method:
Ⅰ Use recursive call;
Ⅱ First define a static array constant to save the result;
Ⅳ Judgment Whether it is an array, if it is a recursive calling method;
Ⅴ If not, put the result into a static array constant;
Ⅵ Return the result (static array constant).
<?php /** * ======================================= * Created by Zhihua_W. * Author: Zhihua_W * Date: 2016/11/28 0003 * Time: 上午 9:11 * Project: PHP开发小技巧 * Power: 实现多维数组转化为一维数组 * ======================================= */ /** * 多维数组转化为一维数组 * @param array $array 多维数组 * @return array $result_array 一维数组 */ function array_multi2single($array) { //首先定义一个静态数组常量用来保存结果 static $result_array = array(); //对多维数组进行循环 foreach ($array as $value) { //判断是否是数组,如果是递归调用方法 if (is_array($value)) { array_multi2single($value); } else //如果不是,将结果放入静态数组常量 $result_array [] = $value; } //返回结果(静态数组常量) return $result_array; } $arr = array( array( 'name' => 'a', 'sex' => 'm', 'sort' => 5 ), array( 'name' => 'c', 'sex' => 'm', 'sort' => 8 ), array( 'name' => 'g', 'sex' => 'm', 'sort' => 3 ), array( 'name' => 'e', 'sex' => 'w', 'sort' => 6 ), array( 'name' => 'b', 'sex' => 'w', 'sort' => 2 ), ); print_r(array_multi2single($arr)); ?>
Array ( [0] => a [1] => m [2] => 5 [3] => c [4] => m [5] => 8 [6] => g [7] => m [8] => 3 [9] => e [10] => w [11] => 6 [12] => b [13] => w [14] => 2 )
The above is the detailed content of PHP development skills (3) - Detailed code explanation for converting multi-dimensional arrays into one-dimensional arrays. For more information, please follow other related articles on the PHP Chinese website!