最近项目都上线了每天巩固一下php知识,下面是关于递归无限分类的比较供大家参考!
数据库一个表就可以了,增加一个parendid字段 也就是子级分类 ,排序大家也可以加一下字段.
CREATE TABLE `category` ( `id` int(11) NOT NULL, `name` varchar(255) CHARACTER SET utf8 DEFAULT NULL, `sort_order` int(11) DEFAULT NULL, `parendid` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of category -- ---------------------------- INSERT INTO `category` VALUES ('1', '手机', null, '0'); INSERT INTO `category` VALUES ('2', '家电', null, '0'); INSERT INTO `category` VALUES ('3', '家具', null, '0'); INSERT INTO `category` VALUES ('4', '诺基亚', null, '1'); INSERT INTO `category` VALUES ('5', '苹果', null, '1'); INSERT INTO `category` VALUES ('6', '电冰箱', null, '2'); INSERT INTO `category` VALUES ('7', '电视机', null, '2'); INSERT INTO `category` VALUES ('8', '柜子', null, '3'); INSERT INTO `category` VALUES ('9', '桌子', null, '3'); INSERT INTO `category` VALUES ('10', '诺基亚3310', null, '4'); INSERT INTO `category` VALUES ('11', '苹果8s', null, '5'); INSERT INTO `category` VALUES ('12', '海尔电冰箱', null, '6'); INSERT INTO `category` VALUES ('13', '长虹电视机', null, '7'); INSERT INTO `category` VALUES ('14', '红木柜子', null, '8'); INSERT INTO `category` VALUES ('15', '红木桌子', null, '9');
php代码部分
<?php /** * Created by PhpStorm. * User: a-4 * Date: 2017/8/3 * Time: 14:12 */ mysql_connect('localhost','root',''); mysql_select_db('ld'); mysql_query('set names utf8'); $sql = "select * from category order by sort_order"; $re = mysql_query($sql); $array = array(); while($row= mysql_fetch_assoc($re)){ $array[]=$row; } //创建树形结构 function createTree($list,$parendid=0,$deep=0){ static $tree =array(); foreach($list as $k=>$rows){ if($rows['parendid'] == $parendid){ //深度字段 次字段来作为分级的标准 $rows['deep'] =$deep; $tree[] = $rows; createTree($list,$rows['id'],$deep+1); } } return $tree; } echo '<pre>'; $tmp= createTree($array); foreach ($tmp as $rows){ echo str_repeat(' ',$rows['deep']*2),$rows['name'],'<br>'; } //print_r ($tmp); ?>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。