# 不递归如何遍历多维数组（维数不定）

PioneerProgram 2015-09-06 11:20:12

``````
\$tree = array (
array (
'ID' => 1,
'PARENT' => 0,
'NAME' => '祖父',
'CHILD' => array (
array (
'ID' => 3,
'PARENT' => 1,
'NAME' => '叔伯'
),
array (
'ID' => 4,
'PARENT' => 1,
'NAME' => '父亲',
'CHILD' => array (
array (
'ID' => 5,
'PARENT' => 4,
'NAME' => '儿子'
)
)
)
)

),
array (
'ID' => 2,
'PARENT' => 0,
'NAME' => '祖母'
)
);
``````

``````
<ul>
<li>祖父
<ul>
<li>叔伯</li>
<li>父亲
<ul>
<li>儿子</li>
</ul>
</li>
</ul>
</li>
<li>祖母</li>
</ul>
``````

...全文
193 点赞 收藏 2

2 条回复

PioneerProgram 2015-09-07

``````\$tree = array (
array (
'ID' => 1,
'PARENT' => 0,
'NAME' => '祖父',
'CHILD' => array (
array (
'ID' => 3,
'PARENT' => 1,
'NAME' => '叔伯'
),
array (
'ID' => 4,
'PARENT' => 1,
'NAME' => '父亲',
'CHILD' => array (
array (
'ID' => 5,
'PARENT' => 4,
'NAME' => '儿子'
)
)
)
)

),
array (
'ID' => 2,
'PARENT' => 0,
'NAME' => '祖母'
)
);
function 递归(\$ar, \$deep=0) {
echo str_repeat("\t", \$deep) . "<ul>\n";
foreach(\$ar as \$item) {
echo str_repeat("\t", \$deep + 1) . "<li>\$item[NAME]";
if(isset(\$item['CHILD'])) {
echo "\n";
递归(\$item['CHILD'], \$deep+2);
}
echo "</li>\n";
}
echo str_repeat("\t", \$deep) . "</ul>\n";
}

``````

``````\$data = array(
array('ID'=>1, 'PARENT'=>0, 'NAME'=>'祖父'),
array('ID'=>2, 'PARENT'=>1, 'NAME'=>'父亲'),
array('ID'=>3, 'PARENT'=>1, 'NAME'=>'叔伯'),
array('ID'=>4, 'PARENT'=>2, 'NAME'=>'自己'),
array('ID'=>5, 'PARENT'=>4, 'NAME'=>'儿子'),
);``````

``````<ul>
<li>祖父
<ul>
<li>叔伯</li>
<li>父亲
<ul>
<li>儿子</li>
</ul>
</li>
</ul>
</li>
<li>祖母</li>
</ul>``````

xuzuning 2015-09-06

``````\$tree = array (
array (
'ID' => 1,
'PARENT' => 0,
'NAME' => '祖父',
'CHILD' => array (
array (
'ID' => 3,
'PARENT' => 1,
'NAME' => '叔伯'
),
array (
'ID' => 4,
'PARENT' => 1,
'NAME' => '父亲',
'CHILD' => array (
array (
'ID' => 5,
'PARENT' => 4,
'NAME' => '儿子'
)
)
)
)

),
array (
'ID' => 2,
'PARENT' => 0,
'NAME' => '祖母'
)
);
function 递归(\$ar, \$deep=0) {
echo str_repeat("\t", \$deep) . "<ul>\n";
foreach(\$ar as \$item) {
echo str_repeat("\t", \$deep + 1) . "<li>\$item[NAME]";
if(isset(\$item['CHILD'])) {
echo "\n";
递归(\$item['CHILD'], \$deep+2);
}
echo "</li>\n";
}
echo str_repeat("\t", \$deep) . "</ul>\n";
}

``````

PHP

1.9w+

“超文本预处理器”，是在服务器端执行的脚本语言，尤其适用于Web开发并可嵌入HTML中。PHP语法利用了C、Java和Perl，该语言的主要目标是允许web开发人员快速编写动态网页。

2015-09-06 11:20