您好,登錄后才能下訂單哦!
最近項目都上線了每天鞏固一下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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。