一、建表(当然我在这里建立的十分简单,仅仅为了实现无限极分类的功能)
CREATE TABLE `cate` ( `cate_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '分类id', `cate_name` varchar(40) NOT NULL COMMENT '分类名称', `cate_pid` int(10) NOT NULL COMMENT '父类id', PRIMARY KEY (`cate_id`) ) ENGINE=MyISAM AUTO_INCREMENT=143 DEFAULT CHARSET=utf8 COMMENT='分类表';
二、假设查出的数据格式如下:
$array = array( array('id' => 1, 'pid' => 0, 'name' => '北京市'), array('id' => 2, 'pid' => 0, 'name' => '上海市'), array('id' => 3, 'pid' => 1, 'name' => '东城区'), array('id' => 4, 'pid' => 1, 'name' => '朝阳区'), array('id' => 5, 'pid' => 1, 'name' => '海淀区'), array('id' => 6, 'pid' => 2, 'name' => '徐汇区'), array('id' => 7, 'pid' => 6, 'name' => '徐家汇'), array('id' => 8, 'pid' => 2, 'name' => '黄浦区'), array('id' => 9, 'pid' => 2, 'name' => '普陀区'), array('id' => 10, 'pid' => 9, 'name' => '曹杨路') );
三、无限极分类实现
<?php function generateTree($array) { //第一步 构造数据 $items = array(); foreach ($array as $value) { $items[$value['id']] = $value; } //第二步 遍历数据 生成树状结构 $tree = array(); foreach ($items as $key => $item) { //若不是顶级分类,则将其本身作为son放置在父类中, //注意:此时放置的是引用, //也就是说,当儿子再次出现儿子的时候,儿子与孙子重新组合成父亲与儿子的形象 //但是,在顶级父类中存放的是儿子的引用,所以,当儿子与孙子被重新组合时,顶级父类中也被修改 if (isset($items[$item['pid']])) { $items[$item['pid']]['son'][] = &$items[$key]; } else { $tree[] = &$items[$key]; } } return $tree; } ?>
点击 "运行实例" 按钮查看在线实例
运行结果如下:
Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 北京市 [son] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 东城区 ) [1] => Array ( [id] => 4 [pid] => 1 [name] => 朝阳区 ) [2] => Array ( [id] => 5 [pid] => 1 [name] => 海淀区 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 上海市 [son] => Array ( [0] => Array ( [id] => 6 [pid] => 2 [name] => 徐汇区 [son] => Array ( [0] => Array ( [id] => 7 [pid] => 6 [name] => 徐家汇 ) ) ) [1] => Array ( [id] => 8 [pid] => 2 [name] => 黄浦区 ) [2] => Array ( [id] => 9 [pid] => 2 [name] => 普陀区 [son] => Array ( [0] => Array ( [id] => 10 [pid] => 9 [name] => 曹扬路 ) ) ) ) ) )
四、代码解释
核心代码为:$items[$item['pid']]['son'][] = &$items[$key];
注意引用的用法很巧妙
参考文章地址:https://blog.csdn.net/tiansidehao/article/details/79025359