这是我的代码, 我需要你的帮助来理解它。
<?php $tree = array(
array(
'name' => 'Item-1',
'children' => array()),
array('name' => 'Item-2',
'children' => array(
array('name' => 'Item-2-1',
'children' => array()),
)),
array('name' => 'Item-3',
'children' => array(
array('name' => 'Item-3-1',
'children' => array()),
array('name' => 'Item-3-2',
'children' => array(
array('name' => 'Item-3-2-1',
'children' => array()),
array('name' => 'Item-3-2-2',
'children' => array()),
array('name' => 'Item-3-2-3',
'children' => array(
array('name' => 'Item-3-2-3-1',
'children' => array()),
)),
)),
)),
);
我需要的是一个递归函数,它将返回所有名称(名称)。 例如:
Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2
........
我的尝试但它似乎对我不起作用
function tree($tree){
foreach ($tree as $key =>$value) {
foreach ($value as $key=>$value){
echo "$value<br>"; }
echo "<br>"; } }
答案 0 :(得分:1)
您可以使用RecursiveArrayIterator
和RecursiveIteratorIterator
$ai = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree));
echo "<pre>";
foreach ( $ai as $value ) {
echo $value, PHP_EOL;
}
输出
Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2
Item-3-2-1
Item-3-2-2
Item-3-2-3
Item-3-2-3-1
答案 1 :(得分:0)
来自http://snipplr.com/view/10200/
// Recursively traverses a multi-dimensional array.
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value);
}else{
echo $key." = ".$value."<br />\n";
}
}
}