How to build unlimited level of menu through PHP and mysql

前端 未结 8 1519
心在旅途
心在旅途 2020-11-29 01:05

Well, to build my menu my menu I use a db similar structure like this

  2  Services                  0
  3  Photo Gallery             0
  4  Home                         


        
8条回答
  •  青春惊慌失措
    2020-11-29 01:22

    I found this way, working with Yii Framework.

    $children = array();
    
    foreach($model as $k => $item){
        if(empty($item->cn_id_menu_padre))
            $children[$item->cn_id] = $item->attributes;
        else
            $children[$item->cn_id_menu_padre]['hijos'][] = $item->attributes;
    }
    
    foreach($children as $k=>$child){
        if(array_key_exists('hijos',$child))
        {
            echo 'li y dentro ul
    '; foreach($child['hijos'] as $hijo){ echo 'li
    '; } } else echo 'li
    '; }

    In case that you need one more level, you could make another level in children array like hijos_de_hijos and do the comparison then in the if statement.

    Oh, of course, to compare if cn_id_menu_padre is empty, the value in the database should be null.

提交回复
热议问题