2012-09-05 53 views
-1

我的表看起來像顯示樹狀菜單

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 

我能夠用遞歸函數也發揮得很好,但現在的要求是沒有遞歸功能。請幫助,我也很困惑與水平領域。

代碼從數據庫中獲取:

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} 
+0

什麼代碼,你有?你做了什麼研究?你認爲它應該如何工作?你有什麼嘗試? – Jelmer

+0

我已經完成了對stackoverflow的研究ñ沒有找到任何幫助,所以我問這裏...關於代碼,即時通訊使用兩個foreach循環來顯示貓ñ子貓..但是我能夠進入只能達到兩個級別 – lonelycrypto

+0

表格在數據庫中?你如何得到它?如果您需要幫助,請提供您的代碼樣本。 – LaGrandMere

回答

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> 
+0

對不起,因爲我提到它必須完成沒有遞歸函數。 – lonelycrypto

+0

你想要做遞歸功能嗎? –

+0

對不起while循環不能用於當前問題..請參閱smarty – lonelycrypto