Recursive function in PHP

recursive function is a function that calls itself repeatedly for a specified condition.
Here is an example function which calls itself 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
<?php
echo '<select name="category">
<option value="0">Root</option>';

$allcats = getTree();

foreach($allcats as $key=>$value)
{
echo "<option value='$key'>$value</option>";
}
echo '</select>';

foreach($allcats as $key=&gt;$value)
{
echo "$value";
}
echo '

';

function getTree($id=0)
{
static $cates = array();
static $times = 0;
$times++;
$result = mysql_query("SELECT category_id,category_name FROM category_table WHERE parent_id=$id ORDER BY category_name");
while($row = mysql_fetch_assoc($result))
{
$cates[$row['category_id']] = str_repeat("|   ",$times-1)."|___".$row['category_name'];
getTree($row['category_id']);
}
$times---;
return $cates;
}
?>

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

Comments are closed.