Jump to content

[SOLVED] Recursive function to loop through nested categories


markwouters

Recommended Posts

Hello,

 

I have a category structure upt to 5 levels deep.

My table looks like this;

CREATE TABLE `categorie` (
`ID` int(11) NOT NULL auto_increment,
`category_name` text NOT NULL,
`parentID` int(11) NOT NULL default '0',
UNIQUE KEY `ID` (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Cats' AUTO_INCREMENT=91 ;

And I would like to get out all sublevelID's of a certain ID i provide to a function. For example if i give the function the ID of a 3rd level cat, it should return all ID's of all it's subcategories and their subcategories.

 

My function looks like this but only returns the subcategories one level deeper, not the ones two level deep. It seems the value I return is overwritten as it loops through the function.

function showlist($parent) {
$result = mysql_query("SELECT ID FROM categorie WHERE parentID='$parent'"); 
while ($line = mysql_fetch_array($result)) { 
if($catlistids!=""){ $catlistids .= ", "; }
$catlistids .= $line["ID"];
showlist($line["ID"]); 
}
return $catlistids;
}

What am I doing wrong here? I tried everything..

 

Thanks a lot!

 

M.

 

Solved!

 

function showlist($parent, &$catlistids="") {

$result = mysql_query("SELECT ID FROM categorie WHERE sublevelID='$parent'");

while ($line = mysql_fetch_array($result)) {

if($catlistids!=""){ $catlistids .= ", "; }

$catlistids .= $line["ID"];

showlist($line["ID"], &$catlistids);

}

return $catlistids;

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.