0

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.

2
  • can u put your tried recursive function? Commented Jul 30, 2012 at 7:23
  • sure, link is added in the question now. Commented Jul 30, 2012 at 9:08

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.