在php中循环结果

时间:2012-12-05 15:27:49

标签: php

我想循环出$ tree数组,如果它有li将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>";
}

以上的输出很可怕。我哪里出错了,如何解决这个问题?

2 个答案:

答案 0 :(得分: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>';
    }
}

}

但上面的代码只适用于深度&lt; = 1 ...对于需要进行递归或循环的更深层树...

答案 1 :(得分: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 />';
  }

}