一、无限级分类
-- 创建表
create table it_category (
cat_id int unsigned primary key auto_increment,
cat_name varchar(50) default ‘‘,
sort_order int default 0,
parent_id int unsigned
);
-- 插入记录
insert into it_category values (75, ‘分类KKK‘, 50, 0);
insert into it_category values (12, ‘分类FFF‘, 50, 75);
insert into it_category values (77, ‘分类AAA‘, 50, 75);
insert into it_category values (34, ‘分类XXX‘, 50, 12);
insert into it_category values (35, ‘分类HHH‘, 50, 12);
insert into it_category values (9, ‘分类QQQ‘, 50, 77);
insert into it_category values (28, ‘分类JJJ‘, 50, 35);
insert into it_category values (19, ‘分类MMM‘, 50, 35);
<?php
//一、这是老师讲的
//首先,得到所有分类数据
mysql_connect(‘127.0.0.1:3306‘, ‘root‘, ‘1234abcd‘);
$sql = "select * from itcast_shop.it_category where 1 order by sort_order";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
//然后,调用递归查找函数
$tree = getTree($list, 0, 0);
//最后,遍历显示
foreach ($tree as $row) {
echo str_repeat(‘ ‘, $row[‘deep‘]);
echo $row[‘cat_name‘];
echo ‘<br>‘;
}
function getTree($arr, $p_id, $deep = 0) {
static $tree = array();
foreach ($arr as $row) {
if ($row[‘parent_id‘] == $p_id) {
$row[‘deep‘] = $deep;
$tree[] = $row;
//找到了一条符合条件的,马上递归向更深层次查找!查找完毕再回来继续本foreach
getTree($arr, $row[‘cat_id‘], $deep + 1);
}
}
//foreach执行完毕,返回结果
return $tree;
}
---------------------------------换个方法------------------------------
<?php
//二、有朋友迷惑于递归函数的return $tree;
//其实递归进去以后,这个return没什么用,因为$tree已经是静态局部变量
//return的作用是foreach执行完毕,返回查找到的数据
//*我们不用return,把$tree作为超全局变量看看
//首先,得到所有分类数据
mysql_connect(‘127.0.0.1:3306‘, ‘root‘, ‘1234abcd‘);
$sql = "select * from itcast_shop.it_category where 1 order by sort_order";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
//然后,调用递归查找函数
getTree($list, 0, 0);
//最后,遍历显示
foreach ($tree as $row) {
echo str_repeat(‘ ‘, $row[‘deep‘]);
echo $row[‘cat_name‘];
echo ‘<br>‘;
}
function getTree($arr, $p_id, $deep = 0) {
foreach ($arr as $row) {
if ($row[‘parent_id‘] == $p_id) {
$row[‘deep‘] = $deep;
$GLOBALS[‘tree‘][] = $row;
//找到了一条符合条件的,马上递归向更深层次查找!查找完毕再回来继续本foreach
getTree($arr, $row[‘cat_id‘], $deep + 1);
}
}
}
二、用php实现打印磁盘文件目录
<?php
function dirTree($path, $deep = 0) {
$dir_handle = opendir($path);
while (($file = readdir($dir_handle)) !== FALSE) {
if ($file == ‘.‘ || $file == ‘..‘) {
} else {
if (is_dir($path . ‘/‘ . $file)) {
echo str_repeat(‘ ‘, $deep);
echo ‘+‘, $file, ‘<br />‘;
dirTree($path . ‘/‘ . $file, $deep + 1);
} else {
echo str_repeat(‘ ‘, $deep);
echo $file, ‘<br />‘;
}
}
}
}
$path = ‘D:\amp\apache\htdocs\study‘;
dirTree($path);