栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP无限级分类实现(递归+非递归)

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP无限级分类实现(递归+非递归)


1,'name'=>'电脑','pid'=>0),      array('id'=>2,'name'=>'手机','pid'=>0),      array('id'=>3,'name'=>'笔记本','pid'=>1),      array('id'=>4,'name'=>'台式机','pid'=>1),      array('id'=>5,'name'=>'智能机','pid'=>2),      array('id'=>6,'name'=>'功能机','pid'=>2),      array('id'=>7,'name'=>'超级本','pid'=>3),      array('id'=>8,'name'=>'游戏本','pid'=>3),  );       $tree array();  //第一步,将分类id作为数组key,并创建children单元  foreach($categories as $category){      $tree[$category['id']] = $category;      $tree[$category['id']]['children'] = array();  }  //第二步,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。  foreach($tree as $key=>$item){      if($item['pid'] != 0){          $tree[$item['pid']]['children'][] = &$tree[$key];//注意:此处必须传引用否则结果不对          if($tree[$key]['children'] == null){              unset($tree[$key]['children']); //如果children为空,则删除该children元素(可选)          }      }  }  ////第三步,删除无用的非根节点数据  foreach($tree as $key=>$category){      if($category['pid'] != 0){          unset($tree[$key]);      }  }     print_r($tree);       $tree $categories;  function get_attr($a,$pid){      $tree array();                                //每次都声明一个新数组用来放子元素      foreach($a as $v){          if($v['pid'] == $pid){                      //匹配子记录              $v['children'] = get_attr($a,$v['id']); //递归获取子记录              if($v['children'] == null){                  unset($v['children']);             //如果子元素为空则unset()进行删除,说明已经到该分支的最后一个元素了(可选)              }              $tree[] = $v;                           //将记录存入新数组          }      }      return $tree;                                  //返回新数组  }   print_r(get_attr($tree,0));

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/229664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号