php - 数据库树到多维数组

标签 php arrays recursion tree

我有一个带有 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/

相关文章:

php - 使用 Ajax 和 mysql 检索数据

Ruby - 方法调用数组中的对象

javascript - 从此对象中选择特定属性值时遇到问题

java - 递归地替换二维数组中的内部数组

ruby - 优化递归搜索

php - 检查用户是否在过去一小时内注册

php - 使用 nginx 的每条路由上的 NotFoundHttpException

php - PHP 的 eval() 如何计算行号?

c - 双参数数组排序

c - C 中的递归和返回语句