Home > Backend Development > PHP Tutorial > Recursively traverse PHP multidimensional array_PHP tutorial

Recursively traverse PHP multidimensional array_PHP tutorial

WBOY
Release: 2016-07-13 10:33:51
Original
866 people have browsed it

Array traversal is a common programming task in PHP, and arrays are divided into one-dimensional arrays, two-dimensional arrays and multi-dimensional arrays. Traversing a one-dimensional array is very simple and can be completed with a for loop. So how should the traversal of two-dimensional arrays and multi-dimensional arrays be implemented? Please see the following procedure:

<?php
/*
*  -------------------------------------------------
*   Author : bkjia
*   Url    : www.bkjia.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.'<br/>';
		}
	}
}
$arr1 = array (1=>array(11,12,13,14=>array(141,142)),2,3,4,5);
echo '<pre class="brush:php;toolbar:false">';
print_r($arr1);
echo '<pre class="brush:php;toolbar:false">';
arr_foreach ($arr1);
?>
Copy after login

The result of running the program is:

Array
(
    [1] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 13
            [14] => Array
                (
                    [0] => 141
                    [1] => 142
                )
        )
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)
11
12
13
141
142
2
3
4
5
Copy after login

The program is very simple, you can see the wonderful use of recursion in it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752392.htmlTechArticleArray traversal is a common programming task in PHP, and arrays are divided into one-dimensional arrays, two-dimensional arrays and Multidimensional array. Traversing a one-dimensional array is very simple and can be completed with a for loop...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template