2012-06-03 85 views
0

我想从这样的数组创建树:构建多维树从Array

阵列(“管理/家”,“管理/家/页”,“管理/测试”,“团队/树/模板','网站');

或者更直观地看作是:

管理/家

管理/家/页

管理/测试

团队/树/模板

site

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

最终产品应当是这样的:

 
    admin 
     home 
      page 
     test 
    team 
     tree 
      template 
    site 

我已经使用本网站的几个不同的解决方案,但我一直没能得到正确的结果。

任何想法或例子,我应该开始将不胜感激,谢谢。

+0

所以你正在处理的数组是一个像“'admin/home”'的字符串数组? – Jeroen

+0

你想要创建什么,HTML输出就像你展示的树(使用'unordered lists')? – Jeroen

+0

是的HTML输出使用预编码和是数组字符串完全一样那 – SineCosine

回答

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>之前关闭列表项。这不是真的应该如何;我猜你实际上应该在最后的<li>中打开嵌套的<ul>,但你可以自己弄清楚。

更新我更新了代码以在某些情况下正确关闭<ul>

+0

不,这是完美的感谢 - 实际上它可能是很好的方式 – SineCosine