我有一个带有 parentid 的简单数据库树,我想读取数据库并得到一个像上面那样的数组
Array
(
Title: Category 1
Children => Array
(
=> Title: Category 1.1
=> Title: Category 1.2
Children => Array
(
=> Title: Category 1.2.1
)
)
)
我尝试用上面的代码实现
function getTree($rootid)
{
$result = =mysql_query("select * from tree where parentid='$rootid'");
while ($row = mysql_fetch_array($result)) {
$arr[]=$row["Title"];
getChilds($row["id"]);
}
}
function getChilds($id)
{
$result = =mysql_query("select * from tree where parentid='$id'");
while ($row = mysql_fetch_array($result)) {
//childers nodes here
$arr[]=$row["Title"];
getChilds($row["id"]);
}
}
}
我有一个关于如何将数组传递给递归函数的问题,所以从我写的最后一个节点继续 child 等等。
它在一个类中实现,我知道我必须传递为 & $arr 但我不确定如何传递
感谢任何帮助
谢谢
最佳答案
尝试这样的事情:
<?php
function getTree($rootid)
{
$arr = array();
$result = mysql_query("select * from tree where parentid='$rootid'");
while ($row = mysql_fetch_array($result)) {
$arr[] = array(
"Title" => $row["Title"],
"Children" => getTree($row["id"])
);
}
return $arr;
}
?>
关于php - 数据库树到多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2178778/