我想循环出 $tree 数组,如果它有子元素,则将 class='parent' 添加到 li,如果没有,则使用默认样式(li)。从所有子 li 中添加和 ul 标签。
print_r($tree)
结果是
Array
(
[0] => stdClass Object
(
[tid] => 6
[vid] => 2
[name] => parent one
[depth] => 0
[parents] => Array
(
[0] => 0
)
)
[1] => stdClass Object
(
[tid] => 14
[vid] => 2
[name] => child one
[depth] => 1
[parents] => Array
(
[0] => 6
)
)
[2] => stdClass Object
(
[tid] => 13
[vid] => 2
[name] => child two
[depth] => 1
[parents] => Array
(
[0] => 6
)
[6] => stdClass Object
(
[tid] => 8
[vid] => 2
[name] =>parent three
[depth] => 0
[parents] => Array
(
[0] => 0
)
我想这样输出结果:
<li class='parent'>
<a href="#">parent one</a><span></span>
<ul class='haschild'>
<li><a href="#">child one/a></li>
<li><a href="#">child two</a></li>
</ul>
</li>
<li><a href="">child three</a></li>
我使用了以下代码,但它无法输出我想要的上述html
foreach($tree as $term){
if($term->depth==0){
echo "<li class='parent'><a href=''>$term->name</a><span></span>";
}
if($term->depth>0){
echo "<ul><li><a href=''>$term->name</a><li></ul>";
}
echo "</li>";
}
上面的输出很糟糕。我哪里出错了,我该如何解决?