PHP实现无限极分类生成分类树的方法
发布:smiling 来源: PHP粉丝网 添加日期:2018-08-31 10:47:53 浏览: 评论:0
现在的分类数据库设计基本都是:每一个分类有一个id主键字段,一个pid指向父类的id,这样便可实现无限级分类,取出的数据就是如下的格式:
- $arr = array(
- array("id" => 1 , "pid" => 0 , 'cat' => '栏目一'),
- array("id" => 2 , "pid" => 0 , 'cat' => '栏目二'),
- array("id" => 3 , "pid" => 1 , 'cat' => '栏目三'),
- array("id" => 4 , "pid" => 2 , 'cat' => '栏目四'),
- array("id" => 5 , "pid" => 1 , 'cat' => '栏目五'),
- array("id" => 6 , "pid" => 5 , 'cat' => '栏目六'),
- array("id" => 7 , "pid" => 5 , 'cat' => '栏目七'),
- array("id" => 8 , "pid" => 6 , 'cat' => '栏目八'),
- array("id" => 9 , "pid" => 1 , 'cat' => '栏目九'),
- array("id" => 10 , "pid" => 0 , 'cat' => '栏目十'),
- array("id" => 11 , "pid" => 10 , 'cat' => '栏目十一'),
- array("id" => 12 , "pid" => 11 , 'cat' => '栏目十二'),
- array("id" => 13 , "pid" => 2 , 'cat' => '栏目十三'),
- array("id" => 14, "pid" => 13 , 'cat' => '栏目十四')
- );
不多说,直接上处理代码:
- //生成无限极分类树
- function make_tree($arr){
- $refer = array();
- $tree = array();
- foreach($arr as $k => $v){
- $refer[$v['id']] = & $arr[$k]; //创建主键的数组引用
- }
- foreach($arr as $k => $v){
- $pid = $v['pid']; //获取当前分类的父级id
- if($pid == 0){
- $tree[] = & $arr[$k]; //顶级栏目
- }else{
- if(isset($refer[$pid])){
- $refer[$pid]['subcat'][] = & $arr[$k]; //如果存在父级栏目,则添加进父级栏目的子栏目数组中
- }
- }
- }
- return $tree;
- }
测试运行:
- $cat = make_tree($arr);
- print_r($cat);
运行结果:
- Array
- (
- [0] => Array
- (
- [id] => 1
- [pid] => 0
- [cat] => 栏目一
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 3
- [pid] => 1
- [cat] => 栏目三
- )
- [1] => Array
- (
- [id] => 5
- [pid] => 1
- [cat] => 栏目五
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 6
- [pid] => 5
- [cat] => 栏目六
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 8
- [pid] => 6
- [cat] => 栏目八
- )
- )
- )
- [1] => Array
- (
- [id] => 7
- [pid] => 5
- [cat] => 栏目七
- )
- )
- )
- [2] => Array
- (
- [id] => 9
- [pid] => 1
- [cat] => 栏目九
- )
- )
- )
- [1] => Array
- (
- [id] => 2
- [pid] => 0
- [cat] => 栏目二
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 4
- [pid] => 2
- [cat] => 栏目四
- )
- [1] => Array
- (
- [id] => 13
- [pid] => 2
- [cat] => 栏目十三
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 14
- [pid] => 13
- [cat] => 栏目十四
- )
- )
- )
- )
- )
- [2] => Array
- (
- [id] => 10
- [pid] => 0
- [cat] => 栏目十
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 11
- [pid] => 10
- [cat] => 栏目十一
- [subcat] => Array
- (
- [0] => Array
- (
- [id] => 12
- [pid] => 11
- [cat] => 栏目十二
- )
- )
- )
- )
- )
- )
如果大家需要这样的组装格式,或者需要该格式方便后续的处理,可以尝试此方法.
Tags: PHP无限极 PHP分类树
- 上一篇:PHP实现的回溯算法示例
- 下一篇:PHP二分查找算法的实现方法示例
相关文章
- ·php无限极分类递归排序(2014-10-22)
- ·php无限极分类递归排序实现方法(2021-04-25)
- ·PHP超牛逼无限极分类生成树方法(2021-05-26)
- ·php通过前序遍历树实现无需递归的无限极分类(2021-06-11)
- ·PHP实现无限极分类的两种方式示例【递归和引用方式】(2021-11-14)
- ·php无限极分类实现方法分析(2021-12-02)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)