Please consider the following table structure:
+----+-----------+--------+
| id | page_name | parent |
+----+-----------+--------+
| 1 | Page 1 | 0 |
+----+-----------+--------+
| 2 | Page 2 | 1 |
+----+-----------+--------+
| 3 | Page 3 | 2 |
+----+-----------+--------+
| 4 | Page 4 | 1 |
+----+-----------+--------+
I wish to loop over each of the pages, indenting them as we go down the tree. The issue is that there are no limits to the level of parenting (i.e. any page can have children). I want to output them in to a <select>
element as follows:
Page 1
Page 2
Page 3
Page 4
I have two functions in the Page class, one is HasChildren()
and the other is FetchChildren()
. Here's what I was thinking, but it only outputs the first level children pages:
while($record = $result->fetch_object())
{
$page = new self($record->id);
$selected = ($page->id == $selectedVal) ? ' selected="selected"' : '';
$select.= '<option value="'. $page->id .'"'. $selected .'>'. $page->name .'</option>';
$i = 1;
$child = $page;
while($child->HasChildren($active))
{
$indentString= ' - ';
for($j = 1; $j <= $i; $j++) { $indentString = ' '.$indentString; }
foreach($child->FetchChildren($active) as $child_child)
{
$selected = ($child_child->id == $selectedVal) ? ' selected="selected"' : '';
$select.= '<option value="'. $child_child->id .'"'. $selected .'>'. $indentString.$child_child->name .'</option>';
$child = $child_child;
}
$i++;
}
}
Can anyone point me in the right direction? It's been a long day, so I'm probably missing something extremely obvious.