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;
}

M.

commented: For putting the effort of using [code] tags and for posting the solution.. +10

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;
}

M.

Great Solution, just what I was looking for. How would I modify this code to indent the subcategories based on level rather than just comma separating the results. Thanks!

I guess you can return them in an array, with wich you can do wathever you want..

Mark.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.