3

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

2 Answers 2

4

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;
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

What if we have depth more than 10.
3

As pointed out over here, using the adjacency list model is not a good approach. You'd better use preorder tree traversal.

Why? Look, most of the time (read: in 99.99% of the cases), the bottleneck of your application WILL be the database. Preorder tree traversal indeed looks more complicated (mainly because it's not modeled after your data in its "natural" state, recursively), but you only need to send a query once and you're done. Beside that, in 99% of the use cases, your application will only display the tree, not modify/reorder it.

2 Comments

i have implement the tree traversal but its really painful on repositioning and move so i am not really sure if i wan to use it.Thanks
I can only agree with Flavius here. I have used the MPTT ever since I found out about it. I only use it for reads though. For adding, moving, or deleting nodes out of the tree I regenerate it using the normal id, parentid recursion method. This way I get the benefits of both worlds with minimal effort.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.