PHP Code:
<?php
class Page {
protected $id;
protected $title;
protected $file;
protected $pages;
public function __construct($id,$title,$file='') {
$this->id = $id;
$this->title = $title;
$this->file = $file;
$this->pages = array();
}
public function getId() {
return $this->id;
}
public function getTitle() {
return $this->title;
}
public function getFile() {
return $this->file;
}
public function getPages() {
return $this->pages;
}
public function addPage(Page $page) {
$this->pages[] = $page;
}
public function getPage($id) {
foreach($this->getPages() as $page) {
if($page->getId() == $id) return $page;
}
return false;
}
}
// test expected SQL result
$rows = array(
array(
'cat_id'=>1
,'cat_name'=>'home'
,'page_id'=>1
,'page_title'=>'home page'
,'page_file'=>'/index.php'
,'subpage_id'=>NULL
,'subpage_title'=>NULL
,'subpage_file'=>NULL
)
,array(
'cat_id'=>2
,'cat_name'=>'contact'
,'page_id'=>2
,'page_title'=>'get in touch'
,'page_file'=>'/get_in_touch.php'
,'subpage_id'=>NULL
,'subpage_title'=>NULL
,'subpage_file'=>NULL
)
,array(
'cat_id'=>2
,'cat_name'=>'contact'
,'page_id'=>3
,'page_title'=>'guestbook'
,'page_file'=>'/guestbook.php'
,'subpage_id'=>NULL
,'subpage_title'=>NULL
,'subpage_file'=>NULL
)
,array(
'cat_id'=>2
,'cat_name'=>'contact'
,'page_id'=>4
,'page_title'=>'feedback'
,'page_file'=>'/feedback.php'
,'subpage_id'=>5
,'subpage_title'=>'further feedback'
,'subpage_file'=>'further_feedback.php'
)
);
$categories = array();
$pk = array();
foreach($rows as $row) {
$index = array_search($row['cat_id'],$pk);
if($index===false) {
$current = new Page($row['cat_id'],$row['cat_name']);
$categories[] = $current;
$pk[] = $row['cat_id'];
} else {
$current = $categories[$index];
}
if(is_null($row['page_id'])) continue;
$currentPage = $current->getPage($row['page_id']);
if($currentPage===false) {
$currentPage = new Page($row['page_id'],$row['page_title'],$row['page_file']);
$current->addPage($currentPage);
}
if(is_null($row['subpage_id'])) continue;
$currentSubPage = $currentPage->getPage($row['subpage_id']);
if($currentSubPage===false) {
$currentPage->addPage(new Page($row['subpage_id'],$row['subpage_title'],$row['subpage_file']));
}
}
echo '<pre>',print_r($categories),'</pre>';
makeMenu($categories);
function makeMenu($pages) {
echo '<ul>',"\n";
foreach($pages as $page) {
echo '<li>',$page->getTitle();
$childPages = $page->getPages();
if(!empty($childPages)) makemenu($childPages);
echo '</li>',"\n";
}
echo '</ul>',"\n";
}
Bookmarks