Php multi-dimensional array Traversal method

Source: Internet
Author: User

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/> ";
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.