我想遍历这个数组并显示'注释'作为要点。
Array
(
[1] => Array
(
[id] => 1
[comment] => a
[parent_id] => 0
[children] => Array
(
[3] => Array
(
[id] => 3
[comment] => c
[parent_id] => 1
[depth] => 0
[child_count] => 0
[children] =>
)
[4] => Array
(
[id] => 4
[comment] => d
[parent_id] => 1
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 1
[child_count] => 2
)
[2] => Array
(
[id] => 2
[comment] => b
[parent_id] => 0
[children] => Array
(
[5] => Array
(
[id] => 5
[comment] => e
[parent_id] => 2
[children] => Array
(
[7] => Array
(
[id] => 7
[comment] => g
[parent_id] => 5
[children] => Array
(
[8] => Array
(
[id] => 8
[comment] => h
[parent_id] => 7
[children] => Array
(
[9] => Array
(
[id] => 8
[comment] => h
[parent_id] => 8
[children] => Array
(
[10] => Array
(
[id] => 8
[comment] => h
[parent_id] => 9
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 1
[child_count] => 1
)
)
[depth] => 2
[child_count] => 1
)
)
[depth] => 3
[child_count] => 1
)
)
[depth] => 4
[child_count] => 1
)
[6] => Array
(
[id] => 6
[comment] => f
[parent_id] => 2
[depth] => 0
[child_count] => 0
[children] =>
)
)
[depth] => 5
[child_count] => 2
)
)
答案 0 :(得分:2)
你需要一点点递归
function traverse_array($array)
{
echo '<ul>';
foreach($array as $element)
{
echo '<li>';
if(isset($element['comment']))
{
echo $element['comment'];
}
if(is_array($element['children']) && count($element['children']) > 0)
{
traverse_array($element['children']);
}
echo '</li>';
}
echo '</ul>';
}
traverse_array($the_big_array);
答案 1 :(得分:0)
在这里,我的 hierTree()函数默认打印嵌套的 ul 或 ol 列表,用于未确定深度的嵌套数组,对于你问题中提供的示例数组,此函数将开箱即用。
function hierTree($arr, $tag = 'ul', $key = 'comment', $lvl = 0)
{
$tabs = (!$lvl)? '': str_repeat("\t", $lvl);
reset($arr);
echo "$tabs<$tag>\n";
while (list(, $v) = each($arr))
{
echo "$tabs\t<li>";
echo "{$v[$key]}";
if (count($v['children']))
{
echo "\n";
hierTree($v['children'], $tag, $key, $lvl +1);
echo "$tabs\t";
}
echo "</li>\n";
}
echo "$tabs</$tag>\n";
}
hierTree($tree);
此函数的输出将很好地缩进,以便于阅读。
此外,如果您执行hierTree($tree, 'ol'); you will get an ordered list. Id you do hierTree($tree, 'ol', 'id');
您将获得一个有序树,并且 id 字段将打印而不是默认的评论字段。
如果您希望每个列表元素具有不同的类,那么您可以更轻松地在CSS上设置样式。 (虽然我建议使用CSS直接后代选择器(“&gt;”))
function hierTree($arr, $tag = 'ul', $key = 'comment', $lvl = 0)
{
$tabs = (!$lvl)? '': str_repeat("\t", $lvl);
reset($arr);
echo "$tabs<$tag class=\"depth$lvl\">\n"; // ← The change is there.
while (list(, $v) = each($arr))
{
echo "$tabs\t<li>";
echo "{$v[$key]}";
if (count($v['children']))
{
echo "\n";
hierTree($v['children'], $tag, $key, $lvl +1);
echo "$tabs\t";
}
echo "</li>\n";
}
echo "$tabs</$tag>\n";
}
此略微修改的版本将为每个列表元素打印 depthN 类。
因此,您可以通过简单的CSS规则(例如ul.depth1 > li { ...
)定位他们的* LI *。