I am trying to build a tree structured menu with the following sort of data stored in a table
id (mediumint8) = record id
title (varchar(128) = menu option title
parent (mediumint8) = record id of the menu option's parent
url (varchar(255) = menu option's url
The data may be stored like this:
id title parent url
1 "option1" 0 "http://www.something.com"
2 "option2" 0 "http://www.somethingelse.com"
4 "option1-1" 1 "http://www.something.com/suboption.html"
6 "option1-1-1" 4 "http://www.something.com/subsuboption.html"
7 "option1-2" 1 "http://www.something.com/suboption2.html"
8 "option2-1" 2 "http://www.somethingelse.com/suboption.html"
9 "option3" 0 "http://www.yetsomethingelse.com"
I am trying to build the tree by first reading all the parent records, THEN reading all the children if the parent record has children (but how can I tell if a parent has children???). Below follows some idea of what I am trying to do.
function treedownmenu() { //not real code, just conceptual stuff
$retval = '';
$nrows = 0;
$result = SELECT everything FROM themenutable WHERE parent=0; //select all parents from the table
$nrows = total number of rows gotten from the select above;
if ($nrows > 0) { //test to see if menu options exist
$retval = 'html startup code'; //if exist start building menu html
} else {
$retval = 'No menu options!'; //no menu. So tell user "NO MENU!"
return $retval;
}
for ($i=0;$i<$nrows;$i++) {
if (the parent record has kids){ // HOW DO I CHECK FOR WHETHER PARENT HAS KIDS???
$retval .= getkids(of this parent record);
} else {
parent record has no kids
}
}
return $retval;
}
function getkids(passed parent id) {
$retval = basically just reads the table for records whose parent=passed parent id;
return $retval;
}
Is there a better way to accomplish this? Thanks in advance!!