php 递归遍历数组

复习PHP中, 简单写下, 练练手。

<?php

/*
*  -------------------------------------------------
*   Author : lellansin
*   Url    : www.lellansin.net
*   Date   : 2014-08-13
*  -------------------------------------------------
*/
function deep_foreach ($arr, $k='', $pre_indent = '') {
	if (!is_array ($arr)) {
		return false;
	}

	$str = $k ? "[$k] => " : '';
	$cur_indent = $pre_indent . "    ";

	echo $pre_indent.$str."Array<br/>$pre_indent(<br/>";

	foreach ($arr as $key => $val ) {
		if (is_array ($val)) {
			deep_foreach ($val, $key, $cur_indent);
		} else {
			echo $cur_indent."[$key] = > ".$val.'<br/>';
		}
	}

	echo $pre_indent.")<br/>";
}

$arr1 = array(array(2,2,8,4=>array(array(5,6,7,8),1)),5,array(5,6,8),3,4);

echo '<pre>';
deep_foreach ($arr1);
echo '</pre>';

输出:

Array
(
    Array
    (
        [0] = > 2
        [1] = > 2
        [2] = > 8
        [4] => Array
        (
            Array
            (
                [0] = > 5
                [1] = > 6
                [2] = > 7
                [3] = > 8
            )
            [1] = > 1
        )
    )
    [1] = > 5
    [2] => Array
    (
        [0] = > 5
        [1] = > 6
        [2] = > 8
    )
    [3] = > 3
    [4] = > 4
)

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>