我在mysql数据库中创建了一个按路径枚举的树表结构。这是我的table:
+----+----------+-----------+-----------+
| id | name | path | id_parent |
+----+----------+-----------+-----------+
| 1 | node1 | /1/ | -1 |
| 2 | node2 | /1/2/ | 1 |
| 3 | node3 | /3/ | -1 |
| 4 | node4 | /3/4/ | 3 |
| 5 | node5 | /3/4/5/ | 4 |
+----+----------+-----------+-----------+
现在我想将其转换为php中的数组,如下所示:
$tree = [
{
name: 'node1', id: 1,
children: [
{ name: 'node2', id: 2 }
]
},
{
name: 'node3', id: 3,
children: [
{
name: 'node4', id: 4 ,
children: [
{ name: 'node5', id: 5 }
]
}
]
}
]
以下功能工作正常,但对于大数据来说却很繁重:
function createTreeDocs($idnode) {
global $CON;
$Q = "SELECT ID,NAME,PATH FROM documents where ID_PARENT={$idnode} order by PATH asc";
$RES = $CON -> query( $Q );
$NUM = $CON -> num( $RES );
$tree = array();
for ($i=0 ; $i<$NUM ; $i++) {
$ROW = $CON -> fetch( $RES );
$node = array("name"=> $ROW["NAME"], "id"=> $ROW["ID"]);
$childs = createTreeDocs($ROW["ID"]);
if (sizeof($childs)>0)
$node["children"] = $childs;
array_push($tree,$node);
}
return $tree;
}
print_r(createTreeDocs(-1));
(我想把它用于jqtree插件)。如果不在php中使用递归函数(仅通过循环),我如何做到这一点?
暂无答案!
目前还没有任何答案,快来回答吧!