当前位置:首页 > PHP教程 > php高级应用 > 列表

php菜单/评论数据递归分级算法的实现方法

发布:smiling 来源: PHP粉丝网  添加日期:2021-12-08 11:36:39 浏览: 评论:0 

这篇文章主要给大家介绍了关于php菜单/评论数据递归分级算法的实现方法,文中通过示例代码介绍的非常详细,对大家学习或者使用php具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。

在开发过程中经常会遇到分级场景,如菜单分级、评论、商品类型分级等;在同一张mysql数据表中可能设计单表结构,如同如下数据:

  1. $menuList = [ 
  2.  [ 'id' => 1,'parent_id' => 0, 'name' => '节点1'], 
  3.  [ 'id' => 2,'parent_id' => 1, 'name' => '节点1-1'], 
  4.  [ 'id' => 3,'parent_id' => 0, 'name' => '节点2'], 
  5.  [ 'id' => 4,'parent_id' => 3, 'name' => '节点2-1'], 
  6.  [ 'id' => 5,'parent_id' => 2, 'name' => '节点1-1-1'], 
  7.  [ 'id' => 6,'parent_id' => 1, 'name' => '节点1-2'], 
  8. ]; 

这时候在处理展示过程就需要将上面的结构转换为更加直观的数据结构, 形如:

  1. $treeList = [ 
  2.  [ 
  3.  children: [ 
  4.   children: [] 
  5.  ] 
  6.  ] 
  7.  [, 
  8.  children: [ 
  9.   children: [] 
  10.  ] 
  11.  ] 
  12. ]; 

算法代码如下:

  1. <?php 
  2.  
  3. class Menu 
  4. { 
  5.  /** 
  6.   * 递归循环菜单列表, 转化为菜单树 
  7.   * @param $treeList 菜单树列表 
  8.   * @param $menuList 菜单列表 
  9.   * @return bool 
  10.   */ 
  11.  public function getMenuTree(&$treeList, $menuList) 
  12.  { 
  13.   // 初始化顶级父节点 
  14.   if (! count($treeList)) { 
  15.    foreach($menuList as $index => $menu) { 
  16.     if ($menu['parent_id'] == 0) { 
  17.      $treeList[] = $menu; 
  18.      unset($menuList[$index]); 
  19.     } 
  20.    } 
  21.   } 
  22.  
  23.   // 递归查找子节点 
  24.   foreach ($treeList as &$tree) { 
  25.    foreach ($menuList as $index => $menu) { 
  26.     if (emptyempty($tree['children'])) { 
  27.      $tree['children'] = []; 
  28.     } 
  29.     if ($menu['parent_id'] == $tree['id']) { 
  30.      $tree['children'][] = $menu; 
  31.      unset($menuList[$index]); 
  32.     } 
  33.    } 
  34.    if (! emptyempty($tree['children'])) { 
  35.     $this->getMenuTree($tree['children'], $menuList); 
  36.    } else { 
  37.     // 递归临界点 
  38.     return false; 
  39.    } 
  40.   } 
  41.  } 
  42.  
  43. } 
  44.  
  45. $menuList = [ 
  46.  [ 'id' => 1,'parent_id' => 0, 'name' => '节点1'], 
  47.  [ 'id' => 2,'parent_id' => 1, 'name' => '节点1-1'], 
  48.  [ 'id' => 3,'parent_id' => 0, 'name' => '节点2'], 
  49.  [ 'id' => 4,'parent_id' => 3, 'name' => '节点2-1'], 
  50.  [ 'id' => 5,'parent_id' => 2, 'name' => '节点1-1-1'], 
  51.  [ 'id' => 6,'parent_id' => 1, 'name' => '节点1-2'], 
  52. ]; 
  53. $treeList = []; 
  54. (new Menu)->getMenuTree($treeList, $menuList); 
  55. print_r($treeList); 
  56. happy coding! 

每一个不曾起舞的日子,都是对生命的辜负 ^-^

Tags: php菜单 php数据递归

分享到: