danielr1996
danielr1996

Reputation: 111

How can I convert a nested set model tree hierarchy to into HTML list elements with PHP?

I have a hierarchical tree stored in a database using the nested set model. How can I print this hierarchy in a <li> list with PHP?

my database table: https://i.sstatic.net/RfhpW.png

my tree structure: https://i.sstatic.net/uTRJK.png

Upvotes: 0

Views: 660

Answers (1)

Satish Sharma
Satish Sharma

Reputation: 9635

you need to recursion try this code or php

$con = mysql_connect("localhost", "root", "");
mysql_select_db("testing_db", $con);

$code_id = 1; // initial of hierarchy // you can put here 1/2/3 as your initial node
print_hierarchy($code_id);

function print_hierarchy($code_id)
{
    echo '<ul>';
    $res = mysql_query("SELECT * FROM `test2` WHERE id='$code_id' LIMIT 1 ") or die(mysql_error());
    if($row = mysql_fetch_assoc($res))
    {

        $left = $row['lft'];
        $right = $row['rgt'];
        echo '<li>'.$row['name'];
        if($left>0 && $left!=$code_id)
        {
            print_hierarchy($left);
        }
        if($right>0 && $right!=$code_id)
        {
            print_hierarchy($right);
        }
        echo '</li>';

    }
    echo '</ul>';   
    return;
}

NOTE : here i am using mysql_* which is deprecated use mysqli_* or pdo

Upvotes: 1

Related Questions