Ok, I have a function that reads through a table in my database where the records are meant to be displayed in a tree structure, and I want a '-' added on the start for each level, ie
Root 1
-Level 1, Item 1
-Level 1, Item 2
Root 2
-Level 1, Item 3
--Level 2 ,Item 1
-Level 1, Item 4
Each item has an id and the id of its parent stored with it so I can construct the table. Getting the things out of the database in the right order is easy, I've already done that. What I can't do is make it add the correct number of dashes. I need to have a variable that each iteration of the function has its own copy of (it's a recursive function btw) and I don't know how to define that. What I have so far is:
function showLevel($sRoot,$levelpre) {
$query = "SELECT id,name FROM uni_tree WHERE parent = $sRoot";
$Results = mysql_query($query);
If (mysql_num_rows($Results) > 0) {
while ($aResult = mysql_fetch_array($Results)) {
echo $levelPre.$aResult[name]."<br>";
$levelPre .= "-";
showLevel($aResult[id],$levelPre);
}
}
}
This calls itself with the id of the record it just retrieved so the next run can get the records that have that parent.
Basically it won't work properly unless either each $levelPre is local to each call or there is another easier way to do it, so my question is how? The answer is probably in the documentation, but I've searched and I couldn't find it.
Thanks in advance.
Root 1
-Level 1, Item 1
-Level 1, Item 2
Root 2
-Level 1, Item 3
--Level 2 ,Item 1
-Level 1, Item 4
Each item has an id and the id of its parent stored with it so I can construct the table. Getting the things out of the database in the right order is easy, I've already done that. What I can't do is make it add the correct number of dashes. I need to have a variable that each iteration of the function has its own copy of (it's a recursive function btw) and I don't know how to define that. What I have so far is:
function showLevel($sRoot,$levelpre) {
$query = "SELECT id,name FROM uni_tree WHERE parent = $sRoot";
$Results = mysql_query($query);
If (mysql_num_rows($Results) > 0) {
while ($aResult = mysql_fetch_array($Results)) {
echo $levelPre.$aResult[name]."<br>";
$levelPre .= "-";
showLevel($aResult[id],$levelPre);
}
}
}
This calls itself with the id of the record it just retrieved so the next run can get the records that have that parent.
Basically it won't work properly unless either each $levelPre is local to each call or there is another easier way to do it, so my question is how? The answer is probably in the documentation, but I've searched and I couldn't find it.
Thanks in advance.