Thanks for the suggestions. Here is a much improved version. The speed is about 10 times that of the previous code. (average of 0.009 seconds on my webserver, which still isn't really fast) It also does css classes for any level, but it does not generate the css.
It now only does one database query and no reading of the directory structure. (disk accesses are generally slow) I had to split it up into 3 functions. Here they are:
`function printGalleryTree($parentid, $ul_id) {
//Get all the albums
$sql = "SELECT id, title, folder, parentid FROM ".prefix("albums");
$result = query($sql);
$albums = array();
while($row = mysql_fetch_array($result)){
array_push($albums, $row);
}
printGalleryTreeItems($albums, $parentid, 0, $ul_id, true);
}`
`function getChildren($albums, $id){
foreach($albums as $album){
if($album['parentid'] == $id){
return true;
}
}
return false;
}`
`function printGalleryTreeItems($albums, $parent, $level, $ul_id){
$sub_ul_id = null;
$count = 1;
if($parent != null){
print "<ul";
if(isset($ul_id)){
print " id=\"".$ul_id."\"";
}
print ">";
}else{
$sub_ul_id = $ul_id;
}
foreach($albums as $album){
if($album['parentid'] == $parent){
if($level == 0 && !is_null($parent)){
print "<li class=\"menutree\">";
}elseif($level > 0){
print "<li class=\"menutree level".$level."\">";
}
if($level > 0 || !is_null($parent)){
//display each child
print "<a href=\"".getMainSiteName()."?album=".$album['folder']."\" title=\"View Trips in ".$album['title']."\">";
print $album['title'];
print "</a>";
}
$children = getChildren($albums, $album['id']);
if($children){
printGalleryTreeItems($albums, $album['id'], $level+1, $sub_ul_id, true);
}
if(isset($sub_ul_id)){
$sub_ul_id = $sub_ul_id.$count;
$count++;
}
if(($level == 0 && !is_null($parent)) || $level > 0){
print "</li>";
}
}
}
if($parent != null){
print "</ul>";
}
}`
Hope this is useful for someone.
Joel