Sunday, February 25, 2007

Ease your recursion

Ever wanted to have an easy way of building a recursive tree ?
Or something like that ?
Or even without understanding much of recursion or always thinking how was this done and so one ?

Well I eased your life a bit ;P



<?php
/**
* Function that builds a category tree with recursion
* (it selects only id, [your specified field] and parent_id
* from the selected table)
*
* @param string $spacer
* @param string $table_name
* @param string $field_name
* @param integer $start_id
* @param string $link
* @param string $request_param
* @param string $link_style
*/
function buildRecursionTree($spacer = '>>' , $table_name ,
$field_name , $start_id = '0' ,
$link , $request_param ,
$link_style) {
global $db;

$sql = "SELECT `id`,`$field_name`,`parent_id`
FROM `$table_name`
WHERE `parent_id`='$start_id'";
$result = $db->query($sql);
while (list($id,$name,$parent_id) = $db->fetch_array($result)) {
$spacer_next = " ".$spacer;
?>
<?=$spacer?>
<a href="'<?="$link?">?<?=$request_param?>=<?=$id?>'
style='<?=$link_style?>' >
<?=$name?>
</a>
<br/>
<?
buildRecursionTree($spacer_next , $table_name ,
$field_name , $id ,
$link , $request_param ,
$link_style);
}
}
?>


And now some sample usage ;)


<?
$spacer = "<img src='images/arrow.png' border='0' />";
$table_name = "categories";
$field_name = "name";
$start_id = "0";
$link = "index.php";
$request_param = "category";
$link_style = "color: #000000; font-family: arial;
font-size: 11px;
text-decoration: none;";
buildRecursionTree($spacer , $table_name , $field_name ,
$start_id ,
$link , $request_param , $link_style);
?>


Well easy enough huh !
See the sample result yourself ;)

2 comments:

Nike shox shoes said...

As to which more appropriate oneself, water like the person, changes in temperature from cicada.

Tiffany Jewelry said...

This is a great post,which has a lot of readers.
Such kind of post giving us various knowaledge,it worthy to read.It is so wonderful.