我在 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>
...它将以项目符号的形式显示我的树,就像我问题的开头一样。无论如何,任何帮助将不胜感激!
查尔斯
最佳答案
您可以使用递归函数调用。
PSEUDCODE(抽象):
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.
我希望这将有所帮助。
关于sql - 如何从闭包表中以 HTML 显示树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12986914/