Maison >développement back-end >tutoriel php >php小代码树形菜单生成
<?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>';
执行结果如图: