Thanks for the feedback!!
I wasn't aware that functions shouldn't print anything. Does it slow down the script?
I'm reading up on 'nested sets' (thank you!) It might take me a little while to figure out what's going on.
Here is my second round of code now with:
-only 1 query to the database
-using str_repeat() function to indent cats
-a for loop in the recursive function to search for subcats
// page to display cats/subcats in tree formation
// Uses the ez_sql Database abstraction layer found here:
// jvmultimedia.com/home/articles.php?articleId=2
// ---------------------------------------------------------
include("ez_sql.php"); // call database connect layer
// sample array name/value
/* print $all[0][0]; // cat_id
print $all[0][1]; // subcat_id
print $all[0][2]; // cat name */
// vars
$all=$db->get_results("SELECT * FROM gal_cat", ARRAY_N); // put all cats into array
$cat_id_array=array(); // push/pop cat id's
$subcounter=0; // to count what subcat level function is on, used for indenting
// recursive function to print second level cats and subcats
// ........................................................
function SubCat($id, $cat_id_array, $subcounter){
global $subcounter;
global $db;
global $all;
// find all cats w/given subcat_id
for($a=0; $a<count($all); $a++){
if($id == $all[$a][1]){
$indent=str_repeat(" ", $subcounter); // indent
print $indent.$all[$a][2]."<BR>\n"; // print subcat
array_push($cat_id_array, $all[$a][0]); // push cat_id to array
// (now have string of cats to go back through)
// recursively call SubCat function for subs of this id & increment subcounter
SubCat($all[$a][0], $cat_id_array, $subcounter++);
} // end if
} // end for
array_pop($cat_id_array); // pop cat_id off array when done with it
$subcounter--; // decrement subcounter
} // end subcat function
// ........................................................
// STARTS HERE: Loop & print through all top level cats
for($i=0; $i<count($all); $i++)
{
if($all[$i][1]==0){ // if subcat_id=0
print "<b>".$all[$i][2]."</b><BR>\n"; // print topcat
array_push($cat_id_array, $all[$i][0]); // push cat_id to array
// subs : go through remaining records for subcats of last cat_id_array value
$last=count($cat_id_array)-1; // because of zero key
SubCat( $cat_id_array[$last], $cat_id_array, $subcounter=0 ); // print subcats if any
print "<BR>";
} // end if
} // end for