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 traversal arrays
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 for traversing arrays: foreach, each, list, and each. let's see how they traverse multi-dimensional arrays.
First, let's look at a traversal of a two-dimensional array. the code is as follows:
- $ Sports = array (
- 'Football' => 'good ',
- 'Canonicalization' => 'very well ',
- 'Running' => 'not good'
- );
- Foreach ($ sports as $ key => $ value ){
- Echo $ key. ":". $ value ." ";
- }
- ?>
The following shows how to traverse 3D arrays.
Example 1 code:
- Function arr_fun ($ arr ){
- If (is_array ($ arr )){
- Foreach ($ arr as $ v ){
- If (is_array ($ v )){
- Arr_fun ($ v );
- } Else {
- Echo $ v ."
";
- }
- }
- } Else {
- Echo $ arr ."
";
- }
- }
Example 2 code:
- /*
- *-------------------------------------------------
- * Url: www.phpfensi.com
- * 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 .'
';
- }
- }
- }
- $ Arr1 = array (1 => array (11,12, 13,14 => array (141,142 );
- Echo'
';
- Print_r ($ arr1 );
- Echo'
';
- 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
- )
Use list and each to traverse two-dimensional arrays. the code is as follows:
- $ Sports = array (
- 'Football' => 'good ',
- 'Canonicalization' => 'Www .phpfensi.com ',
- 'Running' => 'not good'
- );
- While (list ($ key, $ value) = each ($ sports )){
- Echo $ key. ":". $ value ." ";
- }
- ?>