数据库树到多维数组 [英] database tree to multidimensional array

查看:25
本文介绍了数据库树到多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 parentid 的简单数据库树,我想读取数据库并获得一个像上面那样的数组

i have a simple database tree with parentid and i want to read the db and get an array like above

Array
(
 Title: Category 1
 Children => Array
             (
              => Title: Category 1.1

              => Title: Category 1.2
                     Children =>  Array
                               (
                                => Title: Category 1.2.1

                               )
              ) 

)

我尝试用上面的代码实现

I try to implement with above code

    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"]);

      }

    }

}

我有一个关于如何将数组传递给递归函数的问题,因此从我写的最后一个节点继续子节点.

I have a problem on how to pass the array to recursion function so continue children from the last node i wrote and so on.

它在一个类中实现,我知道我必须通过 &$arr 但我不知道如何

Its implement inside a class and i know i have to pass as & $arr but i am not sure how

感谢任何帮助

谢谢

推荐答案

试试这个:

<?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;
}
?>

这篇关于数据库树到多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆