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 |
-
<option value=’0‘>Root</option>’;
-
$allcats = getTree();
-
foreach($allcats as $key=>$value)
-
{
-
echo "<option value=’$key’>$value</option>"
-
}
-
echo ‘</select>’;
-
-
function getTree($id=0)
-
{
-
$times++;
-
$result = mysql_query("SELECT category_id,category_name FROM category_table WHERE parent_id=$id ORDER BY category_name");
-
{
-
getTree($row[‘category_id’]);
-
}
-
$times—;
-
return $cates;
-
}
-
?>
The out put of this program would be the following select box:
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?
What about your data on the table? or they have correct category id and parent id?, let me you show your data.
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.
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;
Your really helpful, I really appreciate that!
Replacing $times–; with $times = $times-1; solved the problem.
Thanks again!