Hi Saracen,
I am currently working on the same problem as you. I have come up with a solution, however there is a bug and it does not do only one query. But itdoes do less queries than alot of category functions I have seen.
I'll explain it here, you'll find the script below. Just a note I do have one extra field for boolean tests to find sub_categories.
First thing it does is set the result_identifier to a variable variable. You will see why later.
Then query dB to get first level of categories. Populate $output with this row's info. Then test for subcats with the child field, if no subcats then get the next record. However, if subcats exist then recall the function for another query using a different result_identifier. This where the variable variable comes in.
This set up allows the script to get all sub_cats and format them as you see fit in any order you want.
The bug I mentioned is that upon each time I go back to previous result, it continues to return records I have already retrieved. This bug is driving me nuts.
Here is the function I am using. Maybe posting it here we can get someone else in on this as well.
function build_category_tree($output="",$pid=0){
global $dbh;
static $i = 1;
$level = "level".$i;
${$level} = mysql_query("
SELECT * FROM categories
WHERE parent_id = $pid AND category_id > 0
ORDER BY name", $dbh);
do{
$output .= "${$level}<br>";
while ($row = mysql_fetch_array(${$level})) {
if ($row[child] != 1) {
$output .= $level." | ".$row[category_id]." | " .$row[name]."<br>";
}else{
$output .= $level." | ".$row[category_id]." | " .$row[name]."<br>";
$i++;
build_category_tree($output,$row[category_id]);
}
}
$i--;
if($i == 0){
break;
}
}while(0);
echo $output;
}
Darin