Let's dash something off:
Save wear and tear on our db: get everything we need once.
select catid, pcatid from the_table
$rows=mysql_num_rows($result);
$tree = array();
for($i=0;$i<$rows;++$i)
{ $row = mysql_fetch_array($result);
$parent = $row['pcatid'];
$cat = $row['catid'];
$tree[$cat]=$parent;
}
Then (for the core of the recursive function) the number of immediate subcategories of catid $cat can be found with
count(array_keys($tree,$cat));
And if you want to know what those subcategories actually are, just leave off the count().
Dunno how you identify the root. I guess it's the one where count(array_keys()) returns 0.
However you do it, that of course is where the recursion starts. Given the catid $root:
function recurse($tree, $catid)
{ $subcats = array_keys($tree,$catid);
$count_subcats = count($subcats);
/* Insert Useful Code Here */
foreach($subcats as $subcat)
{ recurse($tree, $subcat);
}
}
recurse($root);
Obviously the Useful Code depends on your application; and you'd probably be wanting to get more than just raw catids. The raw one-dimensional $tree array above won't be suitable to store additional bits for each category: an associative array would be more useful - the key feature of the above is that catids are used as the $tree array's keys.