PHP recursiveness fail
Posted: February 18th, 2009, 15:52
Im having a bit of trouble with a function - its not working as i expected.
Can anyone see any issues with the following code?
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.
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);
}
}
}
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.