我有一个MySQL数据库,格式如下:
表名:btree_mst字段:id、parent_id、left_node_id、right_node_id、user_name
现在我要做的是以未排序列表格式打印它,如下面的
- 根节点
- 节点A
- 节点A左侧
- 节点A右侧
- 节点B
- 节点B左侧
- 节点B右侧
- 节点A
我试着为此制作一个递归函数,但没有像预期的那样工作。有什么建议吗?
这是我制作的代码,http://pastebin.com/X15qAKaA这个代码中唯一的错误是,它每次都在打印UL。它应该只在级别更改时打印。
提前谢谢。
如果您的DB中没有有序列表,那么递归是合适的。
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();