Page 1 of 1

PHP recursiveness fail

Posted: February 18th, 2009, 15:52
by ProfHawking
Im having a bit of trouble with a function - its not working as i expected.

Can anyone see any issues with the following code?

Code: Select all

function toplevelcategory($category)
{
	// query:
	$sql = mysql_query("SELECT id,parent FROM categories WHERE id = '$category'");
	while ($row = mysql_fetch_array($sql))
	{
		$id = $row['id'];
		$parent = $row['parent'];
		echo "<p>ID: $id, Parent: $parent</p>";
		
		// see if returned parent is 1 (ie a top level category)
		if($parent==1)
		{
			// yes this is a top level category, return it's id
			return $id;
		}
		else
		{
			// no, continue to the next level
			echo " rerunning function ";
			toplevelcategory($parent);
		}
	}
}
in the mysql table there are a load of categories, the parent row has the id of the next level-up category. the top level categories all have a parent of 1.

When i test it it seems to work for the top level categories, but if i feed it a lower level category although it does seem to recursively go through and get there, it doest actually return the top level category id.
:?

Posted: February 18th, 2009, 16:07
by amblin
.

Posted: February 18th, 2009, 16:18
by ProfHawking
ah ha!
i see it now, when the functions are stacked up the returned value only goes up to the next function instead of the page that called it.

just added "return" to the script here

Code: Select all

// no, continue to the next level
			return toplevelcategory($row['parent']);
and all is well :aww:
chars!

Posted: February 18th, 2009, 16:28
by ProfHawking
oh, and
Image :)