原理: pid = 0 的字段为顶级分类, 次级分类的 pid 则为上一级分类的 id, 以此类推来实现无限极分类
无限极分类建表
CREATE TABLE category (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(32) NOT NULL DEFAULT '',
`pid` INT(5) NOT NULL,
......
)Engine=InnoDB DEFAULT CHARSET='utf8';
public function tree($data, $parentid = 0, $space = 0) {
$tree = [];// 字符串重复的次数
$space += 1; if (!empty($data)) { foreach ($data as $key => $value) { if ($value['parentid'] == $parentid) { if ($value['parentid'] != 0) { $value['title'] = str_repeat("—", $space) . $value['title']; } $tree[] = $value;// 将父id为0的数据的id作为参数实现递归
$tree = array_merge($tree, $this->tree($data, $value['id'], $space)); } } } return $tree; }// 处理已获得的数据
public function listDown($data) { $list = [0 => '————请选择————']; if (!empty($data)) { foreach ($data as $key => $value) { $list[$value["id"]] = $value['title']; } } return $list; }