如果我有一个加载到数组($ data)中的数据表(描述树结构),如下所示:
---------------------- | id | name | parent | ---------------------- | 1 | Jack | 0 | //this is the root/top level of tree | 2 | ... | 1 | //name column is irrelevant to problem | 3 | ... | 1 | | 4 | ... | 2 | | 5 | ... | 2 | | 6 | ... | 2 | | 7 | ... | 5 | | 8 | ... | 6 | | 9 | ... | 4 | | 10 | ... | 9 | ----------------------
我想使用递归生成一个ul / li html树,如下所示:
public function get_tree($data, $parent, $depth){
if ($depth > 1000) return ''; // Make sure not to have an endless recursion
$tree = '<ul>';
for($i=0, $ni=count($data); $i < $ni; $i++) {
if($data[$i]['parent'] == $parent){
$tree .= '<li>';
$tree .= '<span>' . $data[$i]['name'] . '</span>';
$tree .= $this->get_tree($data, $data[$i]['id'], $depth+1);
$tree .= '</li>';
}
}
$tree .= '</ul>';
return $tree;
}
出于某种原因,我每次获得额外的ul。我该如何解决这个问题?
答案 0 :(得分:1)
因为你在递归函数中生成了<ul>
。您需要在外部执行<ul>
和</ul>
部分,或者让函数检查它是否是第一次调用它自己和最后一次调用(执行</ul>
)
答案 1 :(得分:1)
function get_tree($data, $parent, $depth){
if ($depth > 1000) return '';
$tree = str_pad(' ',$depth);
for($i=0, $ni=count($data); $i < $ni; $i++) {
if($data[$i]['parent'] == $parent){
$tree .= '<ul>'.PHP_EOL;
$tree .= str_pad(' ',$depth+2);
$tree .= '<li>';
$tree .= '<span>' . $data[$i]['name'] . '</span>';
$tree .= '</li>'.PHP_EOL;
$tree .= get_tree($data, $data[$i]['id'], $depth+1);
$tree .= '</ul>'.PHP_EOL;
}
}
$tree .= str_pad(' ',$depth);
return $tree;
}
我只添加了填充和EOL,以便在简单的测试中,您可以轻松看到树
<ul>
<li><span>one</span></li>
<ul>
<li><span>two</span></li>
<ul>
<li><span>four</span></li>
<ul>
<li><span>nine</span></li>
<ul>
<li><span>ten</span></li>
</ul>
</ul>
</ul>
<ul>
<li><span>five</span></li>
<ul>
<li><span>seven</span></li>
</ul>
</ul>
<ul>
<li><span>six</span></li>
<ul>
<li><span>eight</span></li>
</ul>
</ul>
</ul>
<ul>
<li><span>three</span></li>
</ul>
</ul>