2012-07-30 78 views
0

我在这个格式的MySQL数据库:如何使用PHP打印来自给定数据库结构的二叉树?

表名:btree_mst 字段:ID,PARENT_ID,left_node_id,right_node_id,USER_NAME

现在我要做的就是打印它未有序列表格式像下面

  • 根节点
    • 节点A
      • 节点左
      • 节点A右
    • 节点B
      • 节点B左
      • 节点B右

我试图米ake一个递归函数,但没有按预期工作。 有什么建议吗?

这是我制作的代码,http://pastebin.com/X15qAKaA 这段代码唯一的错误是,它每次都打印UL。它应该只在Level更改时打印。

在此先感谢。

+0

你可以把你尝试过的递归函数? – 2012-07-30 07:23:37

+0

当然,现在在问题中添加链接。 – aslamdoctor 2012-07-30 09:08:22

回答

1

如果您的数据库中没有有序列表,则递归适合。

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