0

我想循环出 $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>";
}

上面的输出很糟糕。我哪里出错了,我该如何解决?

4

2 回答 2

1

尝试这个:

foreach ($tree as $term){
if ($term->depth == 0){
    $children = array();
    foreach ($tree as $term2){
        foreach ($term2->parents as $parent){
            if ($parent == $term->tid){
                $children[] = $term2;
            }
        }
    }

    if (count($children) > 0){
        echo '<li class="parent">';
        echo '<a href="#">' . $term->name . '</a><span></span>';
        echo '<ul class="haschild">';
        foreach ($children as $child){
            echo '<li><a href="#">' . $child->name . '</a></li>';
        }
        echo '</ul>';
        echo '</li>';
    }
    else{
        echo '<li><a href="#">' . $term->name . '</a></li>';
    }
}

}

但是上面的代码仅适用于深度<= 1 ...对于更深的树,您需要进行递归或while循环...

于 2012-12-05T16:15:34.887 回答
0

您的问题是您实际上在该数组中没有任何类似的父子关系。没有嵌入的子元素数组。

你会想让你的数组看起来像这样(JSON):

{
   "parents":[
      {
         "name":"parent 1",
         "children":[
            {
               "name":"child 1"
            },
            {
               "name":"child 2"
            }
         ]
      }
   ]
}

然后,您可以遍历第一级数组项(父项),并为每个项循环其子项:

foreach( $parents as $parent )
{
  echo 'parent: ' . $parent['name'] . '<br />';

  foreach( $parent['children'] as $child )
  {
    echo 'child: ' . $child['name'] . '<br />';
  }

}
于 2012-12-05T15:37:16.360 回答