سؤال

I'm storing some hierarchical data in MySQL. For various reasons, I've decided to use closure tables (instead of nested sets, adjacency lists, and the like). It's been working great for me so far, but now I'm trying to figure out how to actually display this tree in HTML (i.e. with correct indentations).

As an example, let's say I have a tree like so...

  • Food
    • Fruits
      • Apples
      • Pears
    • Vegetables
      • Carrots



My "Foods" table would look like this...

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



My "Closure" table would then look like this...

[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



Now I'm wondering how I would be able to display this correctly in HTML, ideally like this...

<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>

...which would display my tree in bullet form as it is in the beginning of my question. Anyways, any help would be much appreciated!

Charles

هل كانت مفيدة؟

المحلول

You can use recursive function call.

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(Detailed):

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.

I hope this will help.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top