Most of the time, we need to convert a multi-dimensional array into a one-dimensional array, because we only need a one-dimensional array and it is more convenient to use it. in PHP, how can we convert a multi-dimensional array into a one-dimensional array? Let's take a look at the example of converting three multi-dimensional arrays into one-dimensional arrays:
I. Use foreach
Copy codeThe Code is as follows: <? Php
Function arr_foreach ($ arr)
{
Static $ tmp = array ();
If (! Is_array ($ arr ))
{
Return false;
}
Foreach ($ arr as $ val)
{
If (is_array ($ val ))
{
Arr_foreach ($ val );
}
Else
{
$ Tmp [] = $ val;
}
}
Return $ tmp;
}
$ A = array (1, 2 => array (3, 4 => array (5, 6), 7 );
Print_r (arr_foreach ($ ));
?>
2. Use the for loop to traverse only the array with the lower mark of a number
Copy codeThe Code is as follows: <? Php
Function arr_foreach ($ arr)
{
Static $ tmp = array ();
For ($ I = 0; $ I <count ($ arr); $ I ++)
{
If (is_array ($ arr [$ I])
{
Arr_foreach ($ arr [$ I]);
} Else {
$ Tmp [] = $ arr [$ I];
}
}
Return $ tmp;
}
// Call example
$ A = array (1, array (3, array (5, 6), 7 );
Print_r (arr_foreach ($ ));
?>
3. Use the while
Copy codeThe Code is as follows :/**
* Convert a multi-dimensional array to a one-dimensional array
* @ Author echo
* @ Link http://www.jb51.net/
* @ Param array $ arr
* @ Return array
*/
Function ArrMd2Ud ($ arr ){
# Use the first element of the value as the container and assign an address value.
$ Ar_room = & $ arr [key ($ arr)];
# The first container is not an array.
If (! Is_array ($ ar_room )){
# Convert to an array
$ Ar_room = array ($ ar_room );
}
# Pointer down
Next ($ arr );
# Traversal
While (list ($ k, $ v) = each ($ arr )){
# Recursively dig an array, instead of converting it into an array.
$ V = is_array ($ v )? Call_user_func (_ FUNCTION __, $ v): array ($ v );
# Recursive merge
$ Ar_room = array_merge_recursive ($ ar_room, $ v );
# Release the array element of the current base object
Unset ($ arr [$ k]);
}
Return $ ar_room;
}
Call example:
Copy codeThe Code is as follows:
$ Arr = array (1, 2, 3 => array (1, 2, 'ar '=> array (1, 2 => array ('A ', 'B'), array ('ar '=> array (3, 4 )));
Print_r (ArrMd2Ud ($ arr ));
Output:
Copy codeThe Code is as follows:
Array
(
[0] => 1
[1] => 2
[2] => 1
[3] => 2
[4] => 1
[5] =>
[6] => B
[7] => 3
[8] => 4
)