- 论坛徽章:
- 0
|
- <?PHP
- /**
- * 一个无限制分类例子
- * @author jack <warmsun@163.com>;
- */
- /*
- * 创建class数据表
- CREATE TABLE `class` (
- `ID` int(10) unsigned NOT NULL auto_increment,
- `ParentID` int(10) unsigned NOT NULL default '0',
- `Name` varchar(50) NOT NULL default '',
- KEY `class_id` (`ID`)
- ) TYPE=MyISAM AUTO_INCREMENT=11 ;
- #
- # 无限制分类表 `claas`中的数据
- #
- INSERT INTO `class` VALUES (1, 0, '世界');
- INSERT INTO `class` VALUES (2, 1, '中国人民共和国');
- INSERT INTO `class` VALUES (3, 1, '美国');
- INSERT INTO `class` VALUES (4, 1, '俄罗斯');
- INSERT INTO `class` VALUES (5, 2, '北京市');
- INSERT INTO `class` VALUES (6, 2, '海淀区');
- INSERT INTO `class` VALUES (7, 2, '朝阳区');
- INSERT INTO `class` VALUES (8, 6, '车道沟');
- INSERT INTO `class` VALUES (9, 4, '莫斯科');
- INSERT INTO `class` VALUES (10, 6, '小煤厂');
- INSERT INTO `class` VALUES (11, 6, '佟家坟');
- INSERT INTO `class` VALUES (12, 6, '四季青桥');
- */
- mysql_connect('localhost', 'root', '');
- mysql_select_db('test');
- $sql = 'SELECT * FROM class';
- $result = mysql_query($sql);
- //将父类id相同的分类合并,产生二维数组$array
- while ($row = mysql_fetch_array($result)) {
- $array[$row['ParentID']][$row['ID']] = array ('id' =>; $row['ID'], 'parent' =>; $row['ParentID'], 'name' =>; $row['Name']);
- }
- /**
- * @return String //返回一个字符串
- * @param int $category_id //分类的id号
- * @param int $depth //相对于根分类的深度
- * @desc 生成下拉选项
- */
- function genOption($id = 0, $depth = 0) {
- global $array;
- if (!$array[$id])
- return;
- foreach ($array[$id] AS $key =>; $class) {
- echo '<option value="'.$class[id].'">;';
- echo str_repeat("&", $depth);
- echo ($depth) ? ('&'.$class['name']."</option>;\r\n") : ($class['name']."</option>;\r\n");
- genOption($key, $depth +1);
- }
- //如果一个文件要同时调用genOption两次,请注释下面一行.
- unset ($array[$id]);
- }
- ?>;
- <select name="ClassID">;
- <?php
- echo genOption();
- ?>;
- </select>;
复制代码 |
|