显示树状菜单没有递归功能

时间:2012-09-05 09:16:00

标签: php hierarchical-data

我的表看起来像

ID | Parent    | Name    | Level
 1 | 0         | Cat1    | 0
 2 | 1         | SubCat1 | 1
 3 | 0         | Cat2    | 0
 4 | 3         | SubCat2 | 1
 5 | 4         | SubCat3 | 2
 6 | 3         | SubCat4 | 3

我需要按顺序显示数据:

 Cat1
      SubCat1
 Cat2
      Subcat2
          SubCat3
      SubCat4

我能够通过递归函数很好地执行它,但现在的要求是没有递归函数。请帮忙,我也对水平字段感到困惑。

从db获取的代码:

class Sitemap
{ 


public static function getTopCategories()
{
    return self::getCategories('parent=0');
}

public static function getCategories($where='')
{
    if ($where) $where = " WHERE $where";
    $result = mysql_query("SELECT * FROM sitemap $where");

    $categories = array();
   //while ($category = mysql_fetch_object($result, 'Category'))
    while ($category = mysql_fetch_array($result)){
    $my_id = $category['id'];

    $category['children'] = Sitemap::getCategories("parent = $my_id");

            $categories[] = $category;
        }

     mysql_free_result($result);
    return $categories;
  }


 }

要显示的代码(使用Smarty):

{foreach from=$sitemap item=c name=sitemap}
 {if $c.parent ==0 }
<li><h2><a title="{$c.name}" href="{$c.url}">{$c.name}</a></h2><ul>
    {foreach item=d from=$c.children name=sitemap} 
<li><a title="{$d.name}" href="{$d.url}">{$d.name}</a></li>
    {/foreach}
{else}  
<li><h2><a title="{$c.name}" href="{$c.url}">{$c.name}</a></h2><ul>
{/if}
</ul>
</li>
{/foreach}

1 个答案:

答案 0 :(得分:0)

 Try this :->


 with recursive function

 function menu ($p_id='0')
 {

     $q1="select * from menu where p_id='$p_id'";
     $r1=mysql_query($q1) or die(mysql_error());
     while($s1=mysql_fetch_array($r1))
       {
          echo "&nbsp;&nbsp;&nbsp;".$s1['name']."=>";
          $q2="select * from menu where p_id='$s1[id]'";
          $r2=mysql_query($q2) or die(mysql_error()."2nd query error");
          $ro2=mysql_num_rows($r2);
          if($ro2>0)
          {
             $p_id=$s1['id'];
             menu($p_id);
          }

         echo "<br/>";
     }

 }



   echo menu();

没有递归函数::

You have to use procedure language like this

<ul>
    <?php
    $query="select * from table where pid='0'";
     $q1=mysql_query($query);
    while($row=mysql_fetch_array($q1))
     {
        echo "<li>$row[pname]
          // 2nd step check and wirite query and diplay and so on
     <echo "</li>"; 
     }
    ?>
</ul>