Soft-logics
Soft-logics

Reputation: 35

How to display child menu item under their parent item in php?

I need to display all child menu items under their corresponding parent items in php. I have created mysql query but i am unable to get all child items under their parent items.Here is my code:

for ($i = 0; $i < count($menu); $i++) {

    echo'<li><a href="' . $url . $menu[$i]['id'] . '" title="' . $menu[$i]["menu_name"] . '">' . $menu[$i]["menu_name"] . '</a>';
    if ($menu[$i]['parent_id'] != "0" && $menu[$i]['parent_id'] != null) {
        echo'<ul>';
        echo'<li><a href="#" title="' . $menu[$i]["submenu_name"] . '">' . $menu[$i]["submenu_name"] . '</a></li></ul></li>';
    }
}

MySQL Query: SELECT m.id, m.menu_name, sm.parent_id,sm.submenu_name,sm.id
    FROM menu AS m
    LEFT JOIN submenu as sm on (m.id=sm.parent_id)

    Home | Courses | Courses  | 
         | Course-1| Course 2 | 

So i need Course-1 and course 2 under Courses. Please help me where i am going wrong in php code?

Upvotes: 0

Views: 990

Answers (1)

Udan
Udan

Reputation: 5599

Try something like this:

for ($i = 0; $i < count($menu); $i++) {
    echo'<li><a href="'.$url.$menu[$i]['id'].'" title="'.$menu[$i]["menu_name"].'">'. $menu[$i]["menu_name"] . '</a>';
    echo'<ul>'.$menu[$i]['childs'].'</ul></li>';
}

MySQL Query:

SELECT
    m.id, m.menu_name, GROUP_CONCAT(CONCAT("<li><a href=\"#\" id=\"",sm.id,"\">",sm.submenu_name,"</a></li>")) as childs
FROM menu AS m
LEFT JOIN submenu as sm on (m.id=sm.parent_id)
GROUP BY m.id

Upvotes: 1

Related Questions