日期:2014-05-17  浏览次数:20475 次

php无限分类
db设计:
CREATE TABLE IF NOT EXISTS `test` (
	`id` INT(1) NOT NULL AUTO_INCREMENT,
	`path` VARCHAR(255) NOT NULL,
	`name` VARCHAR(255) NOT NULL,
	PRIMARY KEY (`id`))ENGINE = MYISAM DEFAULT CHAR SET ='utf8';
	
INSERT INTO `test` VALUES 
	('', '0', '公司'),
	('', '0-1', '部门一'),
	('', '0-2', '部门二'),
	('', '0-3', '部门三'),
	('', '0-1-1', '小组一'),
	('', '0-1-2', '小组二'),
	('', '0-2-1', '小组三'),
	('', '0-2-2', '小组四');


php代码实现:
<?php
$db = mysql_connect('localhost', 'root', 'zhw') or die('could not conenct to db');
mysql_query("SET charset 'utf8'");
mysql_select_db('test', $db);
$query = mysql_query("SELECT `id`, concat(`path`, '-', id) AS pwd, `name` FROM `test` ORDER BY `pwd`");
while ($row = mysql_fetch_array($query))
{
	$indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', count(explode('-', $row['pwd'])) - 2);
	$option .= "<option value='{$row['id']}'>{$indent}{$row['name']}</option>";
}
echo "<select>{$option}</select>";