Hoping someone out there can help me out on this.
I've built a MySQL database that has Pages, and each Page can live inside another page if needed. Using a Fk key, this means each Page can have infinite subpages, or just 1, 2, 3 etc levels.
My problem is, how can I show a menu for say up to 6 submenus deep?
What I am doing at the moment is finding the Id for a Page, then recursively go back until the Fk is 0 (i.e. root level). This is saved into an array, and then I use a Foreach loop to start from the first Page back to the last Page.
E.g.
Home
History
1900s
1950s
1960s
The Flower Years
1800s
About
Contact
The root dir would show any other pages, in this case About and Contact.
So, using my Foreach loop, I can get the Page Id, Fk and all other Pages for that Fk, but I can't get it to show in the right order.
It keeps showing the level 1 pages first (Home, About, Contact)... THEN the level 2 pages (History), etc etc.
Here's my code:
// Page Level
function getPageLevel ($id, $level = 0) {
/* determine level */
$sql = "SELECT id, page_fk, name
FROM pages
WHERE id='$id'";
if (!($result = mysql_db_query(db, "$sql"))) mysql_msg($sql,mysql_error(),mysql_errno());
while ($row = mysql_fetch_array($result)) {
// call getPageLevel() recursively until root item found
if ($row['page_fk'] != 0) {
$level++;
$this->level_dir[] = $row['id'];
$this->getPageLevel($row['page_fk'], $level);
// get one dir back..
} else {
$level++;
$this->level_dir[] = $row['id'];
} // end getPageLevel()
} // end while
}
// default page is Home
if (empty($id)) $id = 1;
// get Page Level
$admin->getPageLevel($id);
// reverse array
if (is_array($admin->level_dir)) $admin->level_dir = array_reverse($admin->level_dir);
// count array
$num_levels = count($admin->level_dir);
# for each level, show all pages and select the one we are on
foreach ($admin->level_dir as $key=>$value) {
// all level Pages
$admin->menuPages($value, $key);
$tmp_pages_num = $admin->menu_num[$key];
// get Page info
$admin->getPage($value, $key);
// each Menu
for ($i = 0; $i < $tmp_pages_num; $i++) {
// Start UL's
if ($i == 0) {
echo '
<ul>';
}
echo '
<li';
// selected
if ($admin->menu_num_sub[$key][$i] <= 0 && $admin->level_dir[$key+1] == $admin->menu_id[$key][$i]) {
echo ' on"';
} elseif ($admin->level_dir[$key+1] == $admin->menu_id[$key][$i]) {
echo ' class="on"';
} elseif ($admin->menu_num_sub[$key][$i] <= 0) {
echo '"';
}
echo '><a href="?v=page&id=' . $admin->menu_id[$key][$i] . '">' . $admin->menu_name[$key][$i] . '</a>';
// End LI's
if (($i + 1) < $tmp_pages_num) {
echo '</li>';
}
} // end each menu
} // end foreach level