实例: 递归遍历所有目录及子目录和文件
<?php
$path = "要遍历的目录";
//定义函数
function showAll($path){
//判断是不是目录
if(is_dir($path)){
//如果是目录,则打开目录,返回目录句柄
$handle = opendir($path);
echo "<ul>";
//循环从目录句柄中读取
while(false !== $file =opendir($handle)){
//如果读取到".",或".."时,则跳过
if($file =="."||$file==".."){
continue;
}
echo "<li>$file</li>";
//判断读到文件名是不是目录,如果是目录,则开始递归;
if(is_dir($path.'/'.$file)){
showAll($path.'/'.$file);
}
}
echo "</ul>";
//关闭目录句柄
closedir($handle);
}
}
showAll($path);
删除文件
<?php
//删除目录中所有子目录及文件,采用递归的方法
$path = "要遍历删除的目录文件";
//定义函数
function delAll($path){
//判断是不是目录
if(is_dir($path)){
//如果是目录,则打开目录,返回目录句柄
$handle = opendir($path);
echo "<ul>";
//循环从目录句柄中读取
while(false !== $file =opendir($handle)){
//如果读取到".",或".."时,则跳过
if($file =="."||$file==".."){
continue;
}
//如果读取的是目录,则开始递归,如果不是目录,则直接unlink
if(is_dir($path.'/'.$file)){
delAll($path.'/'.$file);
}else{
//不是目录,则直接删除
unlink($path.'/'.$file);
}
}
//关闭目录句柄
closedir($handle);
rmdir($path);
}
}
//调用函数
delAll($path);
#递归方法实现无限极分类
function getTree($list,$pid=0,$level=0) {
static $tree = array();
foreach($list as $row) {
if($row['pid']==$pid) {
$row['level'] = $level;
$tree[] = $row;
getTree($list, $row['id'], $level + 1);
}
}
return $tree;
}