Tuesday, August 12, 2008

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.

2.
’;
3.
$allcats = getTree();
4.
foreach($allcats as $key=>$value)
5.
{
6.
echo ""
7.
}
8.
echo ‘’;
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:

No comments: