I cant guarentee I havent made any syntax mistakes but this should work with one query.
class menuSystem{
var $menu;
var $db; #this variable is my db class assigned from the construct, I havent written the construct in, I can if you need it
function startNav(){
$this->db->runQuery("select * from table order by parent asc");
$menu = array(0 => array('children' => array()));
while ($data = $this->db->fetchArray()) {
$menu[$data['category_id']] = $data;
$menu[(is_null($data['parent']) ? '0' : $data['parent'] )]['children'][] = $data['category_id'];
}
$this->menu = $menu;
$nav = '<ul>';
foreach($menu[0]['children'] as $child_id) {
$nav .= $this->makeNav($menu[$child_id]);
}
$nav .= '</ul>';
}
function makeNav($menu){
$nav_one = '<li>'."\n\t".'<a href="#">'$menu['name'].'</a>';
if(isset($menu['children']) && !empty($menu['children'])) {
$nav_one .= "<ul>\n";
foreach($menu['children'] as $child_id) {
$nav_one .= $this->makeNav($this->menu[$child_id]);
}
$nav_one .= "</ul>\n";
}
$nav_one .= "</li>\n";
return $nav_one;
}
}
EDIT: sorry I use this in my code as a class and thought I had managed to take it out of a class for you but forgot I needed $this->menu
UPDATE: I think the below is out of a class now, sorry for such a long answer
$result = mysql_query("select * from table order by parent_id asc");
$menu = array(0 => array('children' => array()));
while ($data = mysql_fetch_array($result)) {
$menu[$data['category_id']] = $data;
$menu[(is_null($data['parent_id']) ? '0' : $data['parent_id'] )]['children'][] = $data['category_id'];
}
$global_menu = $menu;
$nav = '<ul>';
foreach($menu[0]['children'] as $child_id) {
$nav .= makeNav($menu[$child_id]);
}
$nav .= '</ul>';
function makeNav($menu) {
global $global_menu;
$nav_one = '<li>'."\n\t".'<a href="#">' . $menu['name'].'</a>';
if(isset($menu['children']) && !empty($menu['children'])) {
$nav_one .= "<ul>\n";
foreach($menu['children'] as $child_id) {
$nav_one .= makeNav($global_menu[$child_id]);
}
$nav_one .= "</ul>\n";
}
$nav_one .= "</li>\n";
return $nav_one;
}
Hope it helps
Luke