它的基本原理...跟踪深度,并打印出<ul>
标签</ul>
以将深度推向当前深度。请记住,HTML 不需要</li>
标签,它使生活更轻松。您可以在每个项目之前打印一个<li>
,并让元素根据需要自行关闭。
现在,至于查看列表的细节,这取决于结构(在编辑时,您还不想分享)。不过,我可以想到两种合理的方式来构建这样的列表。
$depth = -1;
// May be foreach($arr as $title => $itemDepth), depending on the structure
foreach ($arr as $item)
{
// if you did the 'other' foreach, get rid of this
list($title, $itemDepth) = $item;
// Note, this only works decently if the depth increases by
// at most one level each time. The code won't work if you
// suddenly jump from 1 to 5 (the intervening <li>s won't be
// generated), so there's no sense in pretending to cover that
// case with a `while` or `str_repeat`.
if ($depth < $itemDepth)
echo '<ul>';
elseif ($depth > $itemDepth)
echo str_repeat('</ul>', $depth - $itemDepth);
echo '<li>', htmlentities($title);
$depth = $itemDepth;
}
echo str_repeat('</ul>', $depth + 1);
这不会生成有效的 XHTML。但是大多数人无论如何都不应该使用 XHTML。