drop table if exists p40_category;
create table p40_category( id mediumint unsigned not null auto_increment comment 'Id', cat_name varchar(30) not null comment '分类名称', parent_id mediumint unsigned not null default '0' comment '上级分类的ID,0:顶级分类', primary key (id))engine=InnoDB default charset=utf8 comment '分类';
无限极分类
// 找一个分类所有子分类的ID
public function getChildren($catId) { // 取出所有的分类 $data = $this->select(); // 递归从所有的分类中挑出子分类的ID return $this->_getChildren($data, $catId, TRUE); } /** * 递归从数据中找子分类 */ private function _getChildren($data, $catId, $isClear = FALSE) { static $_ret = array(); // 保存找到的子分类的ID if($isClear) $_ret = array(); // 循环所有的分类找子分类 foreach ($data as $k => $v) { if($v['parent_id'] == $catId) { $_ret[] = $v['id']; // 再找这个$v的子分类 $this->_getChildren($data, $v['id']); } } return $_ret; }
// 获取树形数据
public function getTree() { $data = $this->select(); return $this->_getTree($data); } private function _getTree($data, $parent_id=0, $level=0){ static $_ret = array(); foreach ($data as $k => $v) { if($v['parent_id'] == $parent_id) { $v['level'] = $level; // 用来标记这个分类是第几级的 $_ret[] = $v; // 找子分类 $this->_getTree($data, $v['id'], $level+1); } } return $_ret; } protected function _before_delete(&$option) { /************** 修改原$option,把所有子分类的ID也加进来,这样TP会一起删除掉 *******/ // 先找出所有子分类的ID $children = $this->getChildren($option['where']['id']); $children[] = $option['where']['id']; $option['where']['id'] = array( 0 => 'IN', 1 => implode(',', $children), ); }
导入测试数据
INSERT INTO `p40_category` (`id`, `cat_name`, `parent_id`) VALUES
(1, '家用电器', 0),
(2, '手机、数码、京东通信', 0),
(3, '电脑、办公', 0),
(4, '家居、家具、家装、厨具', 0),
(5, '男装、女装、内衣、珠宝', 0),
(6, '个护化妆', 0),
(21, 'iphone', 2),
(8, '运动户外', 0),
(9, '汽车、汽车用品', 0),
(10, '母婴、玩具乐器', 0),
(11, '食品、酒类、生鲜、特产', 0),
(12, '营养保健', 0),
(13, '图书、音像、电子书', 0),
(14, '彩票、旅行、充值、票务', 0),
(15, '理财、众筹、白条、保险', 0),
(16, '大家电', 1),
(17, '生活电器', 1),
(18, '厨房电器', 1),
(19, '个护健康', 1),
(20, '五金家装', 1),
(22, '冰箱', 16);