从数组构造多维树

时间:2012-06-03 17:47:07

标签: php arrays multidimensional-array tree iteration

我正在尝试从这样的数组创建一个树:

  

数组('admin / home','admin / home / page','admin / test','team / tree / template','site');

或者更直观地看作:

  

管理员/家

     

管理/家/页

     

管理员/测试

     

团队/树/模板

     

位点

但是,我还需要每个数组的最后一个嵌套字符串变为粗体,表示它本身就是一个网页。

最终产品应如下所示:

    admin
        home
            page
        test
    team
        tree
            template
    site

我在这个网站上使用了一些不同的解决方案,但我未能得到正确的结果。

非常感谢任何关于我应该从哪里开始的想法或例子,谢谢。

1 个答案:

答案 0 :(得分:1)

你可能正在寻找这样的东西:

<?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>