PHP 之递归遍历目录与删除

/**
 * @Description: 递归查询目录文件
 * @Author: Yang
 * @param $path
 * @param int $level
 * @return array
 */
function listDirs($path, $level = 0)
{
    $dir_handle = opendir($path);
    static $tree = array();
    while (false !== $file = readdir($dir_handle)) {
        if ($file == '.' || $file == '..') continue;
        $fileInfo["fileName"] = $file;
        $fileInfo["level"] = $level;
        $tree[] = $fileInfo;
        //判断当前是否为目录
        if (is_dir($path . '/' . $file)) {
            //是目录
            listDirs($path . '/' . $file, $level+1);
        }
    }
    closedir($dir_handle);
    return $tree;
}

$list = listDirs("D:\\wwwroot\\www.phpdemo.com");
foreach ($list as $k => $v) {
    echo "|--".str_repeat("--", $v['level']*2).$v['fileName']."<br>";
}

运行结果以下:php

/**
 * @Description: 递归删除目录文件
 * @Author: Yang
 * @param $path
 * @return bool
 */
function removeDirs($path)
{
    $dir_handle = opendir($path);
    while (false !== $file = readdir($dir_handle)) {
        if ($file == '.' || $file == '..') continue;
        //判断当前是否为目录
        if (is_dir($path . '/' . $file)) {
            //是目录
            removeDirs($path . '/' . $file);
        }else{
            @unlink($path . '/' . $file);
        }
    }
    closedir($dir_handle);
    return @rmdir($path);
}
相关文章
相关标签/搜索