Home >php教程 >php手册 >递归遍历PHP多维数组

递归遍历PHP多维数组

WBOY
WBOYOriginal
2016-06-13 09:39:061006browse

数组的遍历是PHP一个常见的编程任务,而数组又分为一维数组、二维数组和多维数组。一维数组的遍历很简单,直接一个for循环就可以完成。那么二维数组和多维数组的遍历又应该如何实现呢?请看以下程序:

<?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);
?>

程序运行结果为:

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

程序很简单,可以看看递归在其中的妙用。

Statement:
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