2012-10-20 42 views
4

我在MySQL中存储了一些分层数据。由于各种原因,我决定使用闭包表(而不是嵌套集,邻接列表等)。到目前为止,它一直在为我工作,但现在我试图找出如何在HTML中实际显示此树(即使用正确的缩进)。如何以封闭表格的形式在HTML中显示树结构

举个例子,假设我有一棵树,像这样......

  • 食品
    • 水果
      • 苹果
    • 蔬菜
      • 个胡萝卜



我的 “食品” 表是这样的......

[ID] [PARENT_ID] [NAME] 
1  0    Food 
2  1    Fruits 
3  1    Vegetables 
4  2    Apples 
5  2    Pears 
6  3    Carrots 



然后我的 “封闭” 表是这样的。 ..

[PARENT] [CHILD] [DEPTH] 
1   1   0 
2   2   0 
3   3   0 
4   4   0 
5   5   0 
6   6   0 
1   2   1 
1   3   1 
1   4   2 
1   5   2 
1   6   2 
2   4   1 
2   5   1 
3   6   1 



现在,我不知道我怎么会能够在HTML中正确显示这一点,最好是这样的...

<ul> 
    <li>Food 
     <ul> 
      <li>Fruits 
       <ul> 
        <li>Apples</li> 
        <li>Pears</li> 
       </ul> 
      </li> 
      <li>Vegetables 
       <ul> 
        <li>Carrots</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
</ul> 

...这将显示我的树子弹的形式,因为它是在我的问题开始。无论如何,任何帮助将不胜感激!

Charles

+0

你为什么在* Foods *表中有父母身份证?您已经在封闭表中拥有父/子关系。 – Rafa

回答

2

您可以使用递归函数调用。

PSEUDCODE(Abstruct):

function showTree(parent_id){ 

     // retrive child ids from DB using given parent id 
     result = GetChildren(parent_id); 

     while(...){ 

      child_id = result[...]; 

      // Call this function itself 
      showTree(child_id); 

     } 
} 

PSEUDCODE(详细):

function showTree(parent_id){ 

    /* Retrieve child records which has a relationship with the given parent id.*/ 

    SQL = "SELECT * FROM Foods (WHERE PARENT_ID = " + parent_id + ")"; 
    results = executeSQL(SQL); 

    print "<ul>"; 
    i = 0; 
    while(/*results has record*/){ 
     row = results[i]; 

     print "<li>" + row["NAME"] + "</li>"; 

     /* 
     * Make a recursive call here. 
     * Hand out 'ID' as the parameter. 
     * This 'ID' will be received as 'PARENT_ID' in the function called here. 
     */ 
     call showTree(row["ID"]); 

     i = i +1; 
    } 
    print "</ul>"; 

} 
/* 
* Now start calling the function from top of the nodes. 
*/ 
call showFoods(0); // parameter '0' is the root node. 

我希望这将有助于。

+0

这对闭合表不起作用。 –