PHP recursiveness fail

If you touch your software enough does it become hardware?

Moderator: Forum Moderators

Post Reply
ProfHawking
Zombie
Zombie
Posts: 2101
Joined: February 20th, 2005, 21:31

PHP recursiveness fail

Post 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.
:?
amblin
Zombie Spanger
Zombie Spanger
Posts: 2663
Joined: October 22nd, 2004, 11:50

Post by amblin »

.
Last edited by amblin on May 5th, 2014, 18:19, edited 1 time in total.
ProfHawking
Zombie
Zombie
Posts: 2101
Joined: February 20th, 2005, 21:31

Post 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!
ProfHawking
Zombie
Zombie
Posts: 2101
Joined: February 20th, 2005, 21:31

Post by ProfHawking »

oh, and
Image :)
Post Reply