我在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>
...这将以子弹形式显示我的树,就像我在问题的开头一样。无论如何,任何帮助将不胜感激!
查尔斯
答案 0 :(得分:2)
您可以使用递归函数调用。
<强>伪代码(摘要):强>
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);
}
}
<强>伪代码(详细):强>
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.
我希望这会有所帮助。