Blogger Information
Blog 53
fans 3
comment 0
visits 55248
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
20020117-使用递归方法来格式化菜单-php培训线上九期班
邯郸易住宋至刚
Original
711 people have browsed it

使用递归来获取树形菜单的方法

方法一

  1. private function getTreeItems($items)
  2. {
  3. $tree = [];
  4. foreach ($items as $item){
  5. if (isset($items[$item['pid']])){
  6. $items[$item['pid']]['children'][] = &$items[$item['mid']];
  7. }else{
  8. $tree[] = &$items[$item['mid']];
  9. }
  10. }
  11. return $tree;
  12. }

方法二

  1. private function getTree($items,$pid=0)
  2. {
  3. $tree = [];
  4. foreach ($items as $item){
  5. if ($item['pid'] == $pid){
  6. $tree[$item['mid']] = $item;
  7. $tree[$item['mid']]['children'] = $this->getTree($items,$item['mid']);
  8. }
  9. }
  10. return $tree;
  11. }

将无线级菜单格式化为二给菜单的方法

  1. private function formatTree($items,&$res=[])
  2. {
  3. foreach ($items as $key => $item){
  4. if (isset($item['children'])){
  5. $tem = $item['children'];
  6. unset($item['children']);
  7. $res[] = $item;
  8. $this->formatTree($tem,$res);
  9. }else{
  10. $res[] = $item;
  11. }
  12. }
  13. return $res;
  14. }

二级菜单前端遍历需要注意的问题

再进行第二级遍历进,一定要判断是否有二级菜单,如果没有判断,会报错

  1. <div class="menu_dropdown bk_2">
  2. @foreach($menus as $menu)
  3. <dl id="menu-article">
  4. <dt><i class="Hui-iconfont">&#xe616;</i> {{$menu['title']}}<i class="Hui-iconfont menu_dropdown-arrow">&#xe6d5;</i></dt>
  5. @if(isset($menu['children']) && $menu['children'])
  6. <dd>
  7. @foreach($menu['children'] as $m)
  8. <ul>
  9. <li><a href="javascript:;" controller = "{{$m['controller']}}" action = "{{$m['action']}}" onclick="menu_fire(this)"
  10. "title="资讯管理">{{$m['title']}}</a>
  11. </li>
  12. </ul>
  13. @endforeach
  14. </dd>
  15. @endif
  16. </dl>
  17. @endforeach
  18. </div>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments