generate un-ordered list menu from php, mysql

Discussion in 'PHP' started by v.srinath, Feb 14, 2011.

  1. #1
    Hi,
    I need to convert categories table into un-ordered list menu.

    table:
    categories(id int, name varchar(255), parent int);
    id name parent
    1 n1 0
    2 n2 1
    3 n3 1
    4 n4 2
    5 n5 4
    6 n6 0

    I tried using code:

    while ( $row = mysqli_fetch_assoc($query) ) {
    $menu_array[$row['category_id']] = array('name' => $row['category_name'],'parent' => $row['parent_category_id']);
    }

    function generate_menu($parent) {
    $has_childs = false;
    global $menu_array;
    foreach($menu_array as $key => $value) {
    if ($value['parent'] == $parent) {
    if ($has_childs === false) {
    $has_childs = true;
    echo '<ul>';
    }
    echo '<li><a href="#">' . $value['name'] . '</a>';
    generate_menu($key);
    echo '</li>';
    }
    }
    if ($has_childs === true) echo '</ul>';
    }

    generate_menu(0);


    I need to get in this format.
    <ul id="jsddm">
    <li><a href="#">JavaScript</a>
    <ul>
    <li><a href="#">Drop Down Menu</a></li>
    <li><a href="#">jQuery Plugin</a></li>
    </ul>
    </li>
    <li><a href="#">Effect</a>
    <ul>
    <li><a href="#">Slide Effect</a></li>
    </ul>
    </li>
    <li><a href="#">Navigation</a></li>
    </ul>

    help would be appreciated.
     
    v.srinath, Feb 14, 2011 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    
    function menu($parent=0)
    {
            $shown = array();
            $result = mysql_query("SELECT c.* , (SELECT GROUP_CONCAT(x.id) FROM categories as x WHERE x.parent = c.id ORDER BY x.id ASC) as children FROM categories as c WHERE c.parent = '".$parent."' AND c.id != '".$parent."' ORDER BY c.id ASC");
            if(mysql_num_rows($result) > 0)
            {
                while($row = mysql_fetch_array($result))
                {
                    echo '  <li>
                                <a href="#">'.$row['name'].'</a>';
                    
                    if(!is_null($row['children']))
                    {
                        echo '  <ul>';    
                        menu($row['id']);
                        echo '  </ul>';
                    }
                    
                    echo '  </li>';
                }                
            }
    }
        
    echo '<ul id="jsddm">';
    menu();
    echo '</ul>';
    
    PHP:
     
    tvoodoo, Feb 18, 2011 IP