我正在MySQL中存储一些层次数据。由于各种原因,我决定使用闭合表(而不是嵌套集,邻接列表等)。到目前为止,它对我来说一直很好,但是现在我试图弄清楚如何在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
您可以使用递归功能调用。
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.
我希望这会有所帮助。