Recursive functions in PHP

6 Nov, 2008  |  Written by User ImageDan (Who am I?)  |  under Blog, Code Snippets, Tips and Tricks

I thought that i should touch quickly on recursion as it is something that is needed for the below tutorial on creating a conversion script for Wordpress to Joomla

Recursive functions, are functions that call upon themselves repeatedly, in the example in the previous post the function updateCategory is a recursive function

function updateCategory($category, $newParentID)
{
	global $db, $jb, $wp_prefix, $j_prefix;
	$children = $db->get_results("SELECT t.term_id as term_id, t.name as tname, t.slug as tslug, tt.description as description, tt.parent as parent FROM ".$wp_prefix."terms AS t INNER JOIN ".$wp_prefix."term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') and parent=".$category."  ORDER BY t.name");
 
	foreach($children as $child) {
		updateCategory($child->term_id, $newParentID);
		//Check if we are insterting into 1.5 or 1.0.x
		if($j_version=='1.5') {
			//Insert the latest category 
			$jb->query("insert into ".$j_prefix."categories (title, alias, section, description, published) Values('".$child->tname."', '".$child->tslug."', '".$newParentID."', '".$child->description."', 1)");
		}
		else
		{
			$jb->query("insert into ".$j_prefix."categories (title, name, section, description, published) Values('".$child->tname."', '".$child->tslug."', '".$newParentID."', '".$child->description."', 1)");
 
		}
 
		//
		// Insert into our temp storage/reference table
		//
		$jb->query("insert into jos_wp_category_map (wp_cat_id, jos_cat_id, jos_sec_id) values(".$child->term_id.", ".$jb->insert_id.", ".$newParentID.")");
 
	}
 
}

This function uses a recordset of data from the database, it then goes through each of the categories, sub-categories and inserts them in the database in a new level to it’s previous position, the function then calls itself again to check if the current record has children records.

This is a classic example of why recursion is useful and whilst not perfect coding, it does show the usefulness when you need to run a function for deep levels of information and in particular when you do not know how deep you need to go.

So to re-iterate, a recursive function simply calls itself multiple times.

I hope this helps and I hope you find new useful ways to use this, once learning recursive functions, it adds a whole new level to your coding and can cut the amount of lines of code you need to write in half.

Rate this:
2.1

Comments

Post a comment   |   Trackback URI   |   Comments RSS feed

No comments yet.

Trackbacks/Pings

  • No trackbacks or pings yet

Leave a Comment

Comment template by SezWho