您可能正在寻找这样的东西:
<?php
$items = array('admin/home', 'admin/home/page', 'admin/test', 'site', 'team/tree/template');
sort($items);
$previous = array();
foreach ($items as $item) {
$path = explode('/', $item);
// $i is common nesting level of the previous item
// e.g. 0 is nothing in common, 1 is one level in common, etc.
for ($i = 0; $i < min(count($path), count($previous)) && ($path[$i] == $previous[$i]); $i++) { }
// close <ul> from previous nesting levels:
// that is, we close the amount of levels that the previous and this one have NOT in common
for ($k = 0; $k < count($previous)-$i-1; $k++) { echo "</ul>"; }
// $j is the current nesting level
// we start at the common nesting level
for ($j = $i; $j < count($path); $j++) {
// open <ul> for new nesting levels:
// i.e., we open a level for every level deeper than the previous level
if ($j >= count($previous))
echo "<ul>";
echo "<li>";
// make the path bold if the end of the current path is reached
if (count($path)-1 == $j)
echo "<b>" . $path[$j] . "</b>";
else
echo $path[$j];
echo "</li>";
}
$previous = $path;
}
// close remaining <ul>
for ($k = 0; $k < count($previous); $k++) { echo "</ul>"; }
?>
请注意,我对数组进行排序以确保所有嵌套项彼此相邻。
它可能有一些错误,但我想你可以自己解决它们。请注意,我在打开嵌套的<ul>
. 这不是应该的。我猜你实际上应该在那个级别打开嵌套<ul>
在决赛<li>
中,但你可以自己弄清楚。
更新<ul>
我更新了代码以在某些情况下正确关闭's。