hehe, this sounds like a fun script, though you'll probably have to be careful that the categories are not in a circular hierarchy.
Let's try creating a category tree node class:
class CatTreeNode {
var $ID;
var $Parent;
var $Description;
var $subcats;
function CatTreeNode($ID, $Parent, $Description) {
$this->ID = $ID;
$this->Parent = $Parent;
$this->Description = $Description;
$this->subcats = array();
}
//find the subcategories of this category
function findSubCats(&$catnodes) {
$num = 0; //total number of child nodes
//loop through array of uncollected nodes
foreach ($catnodes as $cat) {
if ($cat->getID() == $this->ID) {
$this->subcats[] = $cat;
unset($catnodes[$this->ID]);
$num++;
}
}
//recursively apply to child nodes
for ($i = 0; $i < $num; $i++) {
$this->subcats[$i]->findSubCats($catnodes);
}
}
function getID() {
return $this->ID;
}
function getDescription() {
return $this->Description;
}
function getSubCats() {
return $this->subcats;
}
}
Once we use the findSubCats() function on an array of CatTreeNode objects, this node would store its child nodes, which would in turn find their own child nodes.
Now we have to deal with getting the array of nodes to begin with, and finding the top level nodes:
class CatTree {
var $cats;
function CatTree() {
//array of uncollected nodes
$catnodes = array();
$num = 0; //total number of top level nodes
//extract the whole Category table
$query = mysql_query("SELECT * FROM Category");
//loop through each category entry
while ($row = mysql_fetch_assoc($query)) {
//blank IDs mean top level nodes
if ($row['ID'] == '') {
$this->cats[] = &new CatTreeNode(
$row['ID'],
$row['Parent'],
$row['Description']
);
$num++;
} else {
$catnodes[] = &new CatTreeNode(
$row['ID'],
$row['Parent'],
$row['Description']
);
}
}
//apply the subcategory find to all the top level nodes
for ($i = 0; $i < $num; $i++) {
$this->cats[$i]->findSubCats($catnodes);
}
}
function getCats() {
return $this->cats;
}
}
So to use it:
$nodetree = new CatTree;
$cats = $nodetree->getCats();
Now $cats contains the array of top level categories, from which all the various levels of subcategories can be obtained.
Of course, I havent tested this, so quite a bit of debugging, or even an entire redo, may be in order.