Home > Backend Development > PHP Tutorial > php小代码树形菜单生成

php小代码树形菜单生成

WBOY
Release: 2016-06-20 12:49:13
Original
1146 people have browsed it

<?phpheader("Content-type:text/html; charset=UTF-8"); $mixTree = array();/* * 每个结果中的重点数据两个一个是id一个是指向其父结点id的parent */$mixTree[] = array('id'=>0,'val'=>'顶级菜单1','parent'=>-1);$mixTree[] = array('id'=>1,'val'=>'顶级菜单2','parent'=>-1);$mixTree[] = array('id'=>2,'val'=>'顶级菜单1下的二级菜单1','parent'=>0);$mixTree[] = array('id'=>3,'val'=>'顶级菜单1下的二级菜单2','parent'=>0);$mixTree[] = array('id'=>4,'val'=>'顶级菜单2下的二级菜单1','parent'=>1);$mixTree[] = array('id'=>5,'val'=>'顶级菜单1下的二级菜单2下的三级菜单1','parent'=>3);/* * 通过二维数组把上面的数据挂载成树 */$treeDatas = array();foreach($mixTree as $nodeDatas){    if($nodeDatas['parent']==-1){        $treeDatas[-1][]=$nodeDatas;    }else{        $treeDatas[$nodeDatas['parent']][]=$nodeDatas;    }}/* * 遍历打印其父结点及其子结点 */function traverSesing($nodeDatas,$treeDatas){    echo $nodeDatas['val'];    if(!empty($treeDatas[$nodeDatas['id']])&& is_array($treeDatas[$nodeDatas['id']])){        echo '<ul>';        foreach($treeDatas[$nodeDatas['id']] as $childNodeDatas){            echo '<li>';            traverSesing($childNodeDatas, $treeDatas);            echo '</li>';        }        echo '</ul>';    }    } echo '<ul>';foreach($treeDatas[-1] as $nodeDatas){    echo '<li>';    traverSesing($nodeDatas, $treeDatas);    echo '</li>';}echo '</ul>';
Copy after login

执行结果如图:

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template