Zend - The PHP Company




Searching and Trees

Add Code


Traversing a tree  

Type: code fragment
Added by: phpfarm
Entered: 24/05/2001
Last modified: 05/12/2000
Rating: *** (3 votes)
Views: 11403
I needed a way of organizing information in a mySQL db. I decided that I would have a column called "parent" which would have in it the ID number of the "parent" of this entry. Meaning that if the ID of "table" were 1, then the parent of "leg" would be set to 1. At the time I did not know it, but this is called a tree. Now I needed to be able to fetch the information OUT of the database. I wanted it to show in a select box, parent[indent]child etc....

so, with MUCH help of Michal Baumann of Maryland/Florida, I (she) wrote this (be sure to change it around as much as your heart/program desires/needs):



<?php
// un tree so to speak this data tree
function untree($parent$level)
{
$parentsql mysql_query("select id, domain from domains where underid=$parent order by domain");
// if it is a leaf (no data underneath it) then return
    
if (!mysql_num_rows($parentsql))
    {
    return;
    }
//else echo the result, and recurse the function (so to speak)
    
else
    {
        while(
$branch mysql_fetch_row($parentsql))
            {
            
$echo_this "<option value=$branch[0]>";
//give it some indents in the select box
                
for ($x=1$x<=$level$x++)
                {
                
$echo_this .=  "&nbsp;&nbsp;&nbsp;";
                }

            
$echo_this.="$branch[1]</option>";
//echo the <option> tag
            
echo $echo_this;
//now run this function and find everthing where the parent is equal to the ID of this entry
            
$rename_level $level;
            
untree($branch[0], ++$rename_level);
            }
        }
    }


/* AND HERE IS HOW YOU CALL THE FUNCTION */

// get ALL the entries that have NO parent
$compsql mysql_query("select * from domains where underid=0 order by domain");
    while (
$companys mysql_fetch_array($compsql))
    {
    echo 
"<option value=$companys[id]>$companys[domain]</option>";
//call the untree function and find all the entries that hive THIS entry as a parent (therefore those entries are children of this one)
    
untree($companys[id], 1);
    }
?>


Usage Example


sorry, none


Rate This Script





Search



This Category All Categories