简体   繁体   中英

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

  • Root Node
    • Node A
      • Node A Left
      • Node A Right
    • Node B
      • Node B Left
      • Node B Right

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM