我在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(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.
我希望这将有所帮助。