search
HomeBackend DevelopmentPHP Tutorialthinkphp 关于遍历菜单的问题

在thinkphp中 遍历出数据库的数据显示到模板中,
数据库

CREATE TABLE `cn_menu` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '系统菜单id',  `pid` int(10) unsigned DEFAULT NULL COMMENT '父级id',  `name` varchar(200) DEFAULT NULL COMMENT '菜单名称',  `url` varchar(200) DEFAULT NULL COMMENT '菜单URL',  `params` varchar(200) DEFAULT NULL COMMENT 'URL参数',  `sort` tinyint(4) DEFAULT '1' COMMENT '排序',  `status` tinyint(1) DEFAULT '1' COMMENT '菜单状态(1=显示,2=隐藏,0=删除)',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='系统菜单表';


这是数据库的数据


这个是菜单显示图


这个是模板 代码  但是!这个模板的数据我不要死得,要根据数据库的数据遍历出来的
    <div class="sidebar">        <input type="hidden" value="{:U('SystemFunc/index')}" id="urlAjax">        <ul class="nav" id="nav" >                        <li class="nav-li">                <a href="###" id="aaa">系统菜单 <span class="caret"></span></a>                <ul class="menu">                    <li class="menu-li"><a target="main" href="{:U('SystemFunc/listMenu')}">菜单列表</a></li>                    <!--<li class="menu-li active"><a target="main" href="{:U('SystemFunc/listMenu')}">菜单列表</a></li>-->                    <li class="menu-li "><a target="main" href="{:U('SystemFunc/addMenu')}">添加菜单</a></li>                </ul>            </li>            <li class="nav-li">                <a href="###">系统角色 <span class="caret"></span></a>                <ul class="menu">                    <li class="menu-li"><a target="main" href="{:U('SystemFunc/listOral')}">系统角色</a></li>                    <li class="menu-li"><a target="main" href="{:U('SystemFunc/addOral')}">添加角色</a></li>                </ul>            </li>            <li class="nav-li">                <a href="###">系统管理 <span class="caret"></span></a>                <ul class="menu">                    <li class="menu-li"><a target="main" href="##">管理员</a></li>                    <li class="menu-li"><a target="main" href="{:U('SystemFunc/addAdmin')}">添加管理员</a></li>                </ul>            </li>        </ul>    </div>


1、首先遍历出数据,数据不能是死的,要根据数据库的数据循环出来
2、鼠标点击一下,就隐藏他的下级,  比如:我点击系统菜单,那么 系统菜单下面的菜单列表和添加菜单都(隐藏)收起来!再点击一次菜单列表和添加菜单 显示出来
3、试过很多方法都不管用,新入门的菜鸟求指教,万分感激!!满分奉上


回复讨论(解决方案)

根据pid从数据库取值,至于鼠标点击一下,就隐藏他的下级,这属于前端了,js,或jquery实现

根据pid从数据库取值,至于鼠标点击一下,就隐藏他的下级,这属于前端了,js,或jquery实现

可是代码怎么实现

用sql遍历出数据,然后用两个for循环嵌套,第一个for循环显示pid=0的

  •     系统菜单          第二个for循环显示pid=1,2,3,...的
  • 菜单列表
  •   Ps:提供个思路,如有不对勿喷!

    首先在后台中将pid==0的节点找出来组成数组arr_node,然后foreach该数组,将pid==id的子数组找出来存放在之前数组中,记key为son_node,即arrnode['son_node']=array(...)。
    然后在前台遍历输出,

                  


  •                 {$vo.name} 
                    

                 
                          
    • {$son.name}
    •                                    
                      

               

  • 搞个 二维数组就可以啦

    php无限极分类技术,自行百度。
    推荐你去慕课网看看搜搜你会有很大的收获!!!
    求给分!!!
    我不能给你代码,但我可以给你指条路!

    先建立个获取数据并将其转换成树型结构的递归函数,这个函数可以放到公众目录的函数文件中

    function getTree($data,$pid){    if (!is_array($data) || empty($data) ) return false;    $tree = array();    foreach ($data as $k => $v) {        if ($v['pid'] == $pid) { //当相等时,说明此数组为上个数组的子目录            $v['pid'] = getTree($data,$v['id']);//将子数组的内容遍历后赋给上级数组的pid键,html页面上循环时用到此内容            $tree[] = $v;            unset($data[$k]); //删除遍历过的数组数据        }    }    return $tree;}


    在控制器里建个方法,调用数据,并传到函数里
    public function showMenu(){	$m = M('cn_menu')->field(true)->select();	$d = getTree($m,0);	$this->assign('menu',$d);}




    HTML页面显示内容,

    <div class="sidebar">        <input type="hidden" value="{:U('SystemFunc/index')}" id="urlAjax">        <ul class="nav" id="nav" >            <volist name ="menu" id="vo">             <li class="nav-li">                <a href="###" id="aaa">{$vo.name} <span class="caret"></span></a>                <ul class="menu">                <volist name="vo['pid']" name="vi">                    <li class="menu-li"><a target="main" href="{:U('SystemFunc/listMenu')}">{$vi.name}</a></li>                </volist>                </ul>            </li>            </volist>        </ul>    </div>


    整体原理就是,通过递归函数循环遍历多维数组,生成有对应关系的树型数组,代码全手写,有部分参考别人的,刚好我也在用这块的内容,给你看看

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

    ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

    Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

    You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

    PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

    Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

    PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

    ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

    PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

    APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

    Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

    Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

    PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

    PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

    PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

    PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)