Ok, I'll try to expain what this code does. I have a "Domain" tree table with domainid (PK), parentid, and some other fields. This snippet from a file called viewdomains.php just shows a simple tree with a two hyphen indent for every child:
Domain1
--Domain2
----Domain2a
--Domain3
----Domain3a
------Domain3a-x
etc.
#Begin Snippet ViewDomains.php
#Show chosen top level (ROOT or sn[domainid])
$sql="SELECT * FROM $tbldomains WHERE domainid=$slevel";
$r=odbc_exec($h,$sql);
if (!$r) {die("Query Failed. $sql");}
while (odbc_fetch_row($r)) {
$dn=GetFieldsDomains($r);
echo '<tr class="light">';
echo '<td>'.$dn['code'].'</td>';
echo '<td>'.$dn['description'].'</td>';
echo '</tr>';
$flag=true; #needed to alternate rows
$z=DomainTree($dn['domainid'],1,$h);
}
#End Snippet
The important part is last line where the function DomainTree() is called. Here's the function:
#Function DomainTree
function DomainTree($id,$indent,$h) {
$e=$GLOBALS['tbldomains'];
$sql="SELECT * FROM $e WHERE parentid=$id ORDER BY code";
$f=odbc_exec($h,$sql);
if (!$f) {die("Query Failed. [functions.php DomainTree]");}
$s=str_repeat("--",$indent);
while (odbc_fetch_row($f)) {
$fn=GetFieldsDomains($f);
if ($GLOBALS['flag']) { echo '<tr class="med">'; }
else { echo '<tr class="light">'; }
echo '<td>'.$s.' '.$fn['code'].'</td>';
echo '<td>'.$fn['description'].'</td>';
echo '</tr>';
$GLOBALS['flag']=!$GLOBALS['flag'];
$e=DomainTree($fn['domainid'],$indent+1,$h);
}
return true;
#End Function DomainTree
Notice how DomainTree() calls itself. This is the whole trick. I have other, more complicated examples where I'm pulling information from another table and displaying it under the proper domain, but the concept is the same.