Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

php - database tree to multidimensional array

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.

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

Any help appreciated

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try something like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...