Recursive function in PHP

recursive function is a function that calls itself repeatedly for a specified condition.
Here is an example function which calls iteself to perform a tree structure for a category table
Here is the category table:

category_id parent_id category_name
1 0 CMS
2 0 Blogs
3 0 Forums
4 0 E-Commerce
5 1 Joomla
6 1 Mambo
7 6 Templates
8 6 Mods/Components
9 4 OSCommerce
10 2 Wordpress
11 10 Themes
12 10 Plugins

  1. <?php echo ‘<select name="category">
  2. <option value=’0‘>Root</option>’;
  3. $allcats = getTree();
  4. foreach($allcats as $key=>$value)
  5. {
  6. echo "<option value=’$key’>$value</option>"
  7. }
  8. echo ‘</select>’;
  9.  
  10. function getTree($id=0)
  11. {
  12. static $cates = array();
  13. static $times = 0;
  14. $times++;
  15. $result = mysql_query("SELECT category_id,category_name FROM category_table WHERE parent_id=$id ORDER BY category_name");
  16. while($row = mysql_fetch_assoc($result))
  17. {
  18. $cates[$row[‘category_id’]] = str_repeat("|   ",$times-1)."|___".$row[‘category_name’];
  19. getTree($row[‘category_id’]);
  20. }
  21. $times—;
  22. return $cates;
  23. }
  24. ?>

The out put of this program would be the following select box:

5 comments:

  1. Bas, 29. May 2008, 19:24

    Thanks,

    I have a problem: My table setup and script are the same as in the example.
    But when I run the script it doesn’t show the same output as in your example.

    It shows:

    Root
    |__Blogs
    | |__Wordpress
    | | |__Plugins
    | | | |__Themes
    | | | | |__CMS
    | | | | | |__Joomla
    | | | | | | |__Mambo
    etc….

    How can I solve this, so it shows the correct tree structure?

     
  2. phpbits, 31. May 2008, 9:55

    What about your data on the table? or they have correct category id and parent id?, let me you show your data.

     
  3. Bas, 31. May 2008, 11:18

    They do have the correct id’s. This is what my table setup looks like:

    Table: tree_test

    +————-+———–+—————————–+
    | category_id | parent_id | category_name |
    +————-+———–+—————————–+
    | 1 | 0 | CMS
    | 2 | 0 | Blogs
    | 3 | 0 | Forums
    | 4 | 0 | E-Commerce
    | 5 | 1 | Joomla
    | 6 | 1 | Mambo
    | 7 | 6 | Templates
    | 8 | 6 | Mods/Components
    | 9 | 4 | OSCommerce
    | 10 | 2 | Wordpress
    | 11 | 10 | Themes
    | 12 | 10 | Plugins
    +————-+———–+—————————–+

    As you can see, it’s exactly the same table setup as yours.
    I don’t see why it’s not working.

     
  4. phpbits, 31. May 2008, 11:56

    Sorry, my editor has collapsed the code, try the below:

    In this part:

    //……….
    $times—;
    return $cates;
    //…..

    It’s not $times—

    It should be $times– [double - sign for decrement]

    or $times = $times-1;

     
  5. Bas, 31. May 2008, 13:03

    Your really helpful, I really appreciate that! :)

    Replacing $times–; with $times = $times-1; solved the problem.

    Thanks again!

     

Write a comment: