In php, arrays are classified into many types, such as one-dimensional arrays, two-dimensional arrays, and three-dimensional or multi-dimensional arrays. Next I will introduce php to traverse multi-dimensional arrays. If you need them, refer to them.
In php, there are three functions to traverse Arrays: foreach, each, list & each. Let's see how they traverse multi-dimensional arrays.
First look at a traversal of two-dimensional array
| The Code is as follows: |
Copy code |
|
<? Php
$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'very well ',
'Running' => 'not good'
);
Foreach ($ sports as $ key => $ value ){
Echo $ key. ":". $ value. "<br/> ";
}
?> |
The following shows how to traverse 3D arrays.
Example 1
| The Code is as follows: |
Copy code |
|
Function arr_fun ($ arr ){
If (is_array ($ arr )){
Foreach ($ arr as $ v ){
If (is_array ($ v )){
Arr_fun ($ v );
} Else {
Echo $ v. "<br> ";
}
}
} Else {
Echo $ arr. "<br> ";
}
} |
Example 2
| The Code is as follows: |
Copy code |
|
<? Php
/*
*-------------------------------------------------
* Url: www. bKjia. c0m
* Date: 2011-03-09
*-------------------------------------------------
*/
Function arr_foreach ($ arr)
{
If (! Is_array ($ arr ))
{
Return false;
}
Foreach ($ arr as $ key => $ val)
{
If (is_array ($ val ))
{
Arr_foreach ($ val );
}
Else
{
Echo $ val. '<br/> ';
}
}
}
$ Arr1 = array (1 => array (11,12, 13,14 => array (141,142 );
Echo '<pre> ';
Print_r ($ arr1 );
Echo '<pre> ';
Arr_foreach ($ arr1 );
?>
Output result
Array
(
[1] => Array
(
[0] => 11
[1] => 12
[2] => 13
[14] => Array
(
[0] = & gt; 141
[1] => 142.
)
)
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
11
12
13
141
142
2
3
4
5 |
Traverse two-dimensional arrays using list and each
| The Code is as follows: |
Copy code |
|
<? Php
$ Sports = array (
'Football' => 'good ',
'Canonicalization' => 'www. bKjia. c0m ',
'Running' => 'not good'
);
While (list ($ key, $ value) = each ($ sports )){
Echo $ key. ":". $ value. "<br/> ";
}
?> |