aslamdoctor
aslamdoctor

Reputation: 3935

How to Print Binary Tree from the given Database Structure using PHP?

I have a MySQL database in this format :

table name : btree_mst fields : id, parent_id, left_node_id, right_node_id, user_name

Now what I have to do is print it in the Un-ordered list format like below

I tried to make a recursive function for that but didn't work as expected. Any suggestions ?

Here is the Code I made, http://pastebin.com/X15qAKaA The only bug in this code is, it is printing UL every time. It should print only when the Level is changed.

Thanks in advance.

Upvotes: 0

Views: 1748

Answers (1)

Bekzat Abdiraimov
Bekzat Abdiraimov

Reputation: 110

If you do not have ordered list in your DB, recursion is suitable.

class A
{
    private $a = array(
        array(
            'id' => 1,
            'parent_id' => 0,
            'title' => 'ROOT'
        ),
        array(
            'id' => 2,
            'parent_id' => 1,
            'title' => 'A'
        ),
        array(
            'id' => 3,
            'parent_id' => 1,
            'title' => 'B'
        ),
        array(
            'id' => 4,
            'parent_id' => 2,
            'title' => 'A left'
        )
    );//your database values

    public function buildTree()
    {
        $aNodes = array();
        $iRootId = 1;//your root id
        foreach ($this->a AS $iK => $aV)
        {
            if($aV['id'] == $iRootId)
            {
                unset($this->a[$iK]);
                $aNodes[$aV['id']] = $aV;
                $aNodes[$aV['id']]['childs'] = $this->getChilds($aV['id']);
            }

        }

        print_r($aNodes);//print tree
    }

    private function getChilds($iParentId)
    {
        $aChilds = array();
        foreach ($this->a AS $iK => $aV)
        {
            if($aV['parent_id'] == $iParentId)
            {
                unset($this->a[$iK]);
                $aChilds[$aV['id']] = $aV;
                $aChilds[$aV['id']]['childs'] = $this->getChilds($aV['id']);
            }

        }

        return $aChilds;
    }

}

$o = new A();
$o->buildTree();

Upvotes: 1

Related Questions