This article mainly introduces three PHP multi-dimensional array to one-dimensional array method examples, which are implemented by using the foreach, for, and while loop methods, respectively, for more information about how to convert a multi-dimensional array into a one-dimensional array, we only need one-dimensional array, which is more convenient to use, in PHP, how does one 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
The code is as follows: 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
The code is as follows: Function arr_foreach ($ arr)
{
Static $ tmp = array ();
For ($ I = 0; $ 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
The code is as follows :/**
* Convert a multi-dimensional array to a one-dimensional array
* @ Author echo
* @ Link http://www.bitsCN.com/
* @ 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:
The 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:
The code is as follows:
Array
(
[0] => 1
[1] => 2
[2] => 1
[3] => 2
[4] => 1
[5] =>
[6] => B
[7] => 3
[8] => 4
)