Directory
- 1 Array_reduce Function method
- 2 Array_walk_recursive Function method
- 3 Array_map Function method
Suppose you have the following two-dimensional array:
$user =Array' 0 ' + =Array' id ' =100,' Username ' =' A1 '),' 1 ' + =array ( ' id ' = 101, username ' = ' A2 '), ' 2 ' + array ( ' id ' = 102, username ' + ' A3 '), ' 3 ' = Span class= "Hljs-keyword" >array ( ' id ' = 103, username ' = ' A4 '), ' 4 ' + array ( ' id ' = 104, username ' + ' A5 ');
Now to convert to a one-dimensional array, there are two things:
One is to convert the specified column into a one-dimensional array, which is summarized in another article: PHP Extracts a multidimensional array of methods to specify a column.
Now let's focus on the second case, which is to convert all the values into one-dimensional arrays, and the same key values will not be overwritten, and the converted one-dimensional array would be:
Array (' A5 ');
There are several methods.
1 array_reduce Function Method
Using the Array_reduce () function is a faster method:
($result, $value) { Array ())
Because the array_merge
function merges the arrays of the same string key names, you must first use the array_value
fetch values and then merge them.
If the second dimension is a numeric key name, such as:
Array (Array ( ' A1 '), Array (Array (array ( ' A5 '),);
So that's it for you:
Array ())
2 array_walk_recursive Function Method
With the array_walk_recursive () function, it is very flexible to convert an array of any dimension into a one-dimensional array.
function(& $result) { Array_push ($result, $value);});
For example, the following multidimensional array:
Array (Array ( ' A1 '), Array (Array ( ' A4 ' ),);
With this method, it becomes:
Array (' A4 ');
3 Array_map Function Method
In array_map
array_reduce
the same way as the function, as follows:
$result = [];array_map (& $result) { $result = Array_merge ($result, Array_values ($ value));}, $user);
Just need to declare an empty $result
array more.
In addition, the method can be used, array_walk
and the foreach
cyclic method, the principle and the same as above.
A summary of methods for converting a PHP two-dimensional array (or any array of dimensions) into a one-dimensional array