文件的递归与删除

递归

<?php
$path="E:/php";


function readdiguo($path,$deep=0)
{
    $dir_handle=opendir($path);
    while(false!==$file=readdir($dir_handle))
    {
        if($file=='.' || $file=='..')continue;
        //输出该文件
        echo str_repeat('&nbsp; ',$deep*4).$file."<br />";
        //判断当前是否是目录
        if(is_dir($path.'./'.$file))
        {
            //是目录
            $func_name=__FUNCTION__;//得到当前函数名
            $func_name($path.'./'.$file,$deep+1);
        }
        
    }
}
readdiguo($path);
?>

递归到数组

<?php
$path="E:/php";
$list=readdirQiantao($path);
foreach ($list as $first_key=>$first)
{
    echo $first_key."=".$first["name"]."<br />";
    if($first["type"]=='file')continue;
    foreach ($first["nested"] as $two_key=>$two)
    {
        echo "&nbsp;".$two_key."=".$two["name"]."<br />";
    }
}
function readdirQiantao($path)
{
    $nested=array();//存储当前目录下文件
    $dir_handle=opendir($path);
    while(false!=$file=readdir($dir_handle))
    {
        if($file=='.'||$file=="..")continue;
        
        //创建当前文件信息
        $fileinfo=array();
        $fileinfo["name"]=$file;
        
        //判断是否为目录
        if(is_dir($path.'/'.$file))
        {
            //是目录
            $fileinfo["type"]="dir";
            $func_name=__FUNCTION__;
            $fileinfo["nested"]=$func_name($path."/".$file);
        }else
        {
            //是文件
            $fileinfo["type"]="file";
        }
        //存入数组
        $nested[]=$fileinfo;
    }
    closedir($dir_handle);
    return $nested;
    
}
?>

递归删除文件

<?php
$path="./pp";
var_dump(reDirs($path));
function reDirs($path)
{
    $dir_handle=opendir($path);
    while(false!=$file=readdir($dir_handle))
    {
        if($file=='.'||$file=='..')continue;
        
        //判断当前是否目录
        if(is_dir($path.'/'.$file))
        {
            //是目录
            $func_name=__FUNCTION__;
            $func_name($path.'/'.$file);
        }else
        {
            //是文件
            unlink($path.'/'.$file);
        }
    }
    closedir($dir_handle);
    return rmdir($path);//删除目录
}
?>

 

posted @ 2016-01-12 22:06  自由无风  阅读(273)  评论(0编辑  收藏  举报