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);
}
相關文章
相關標籤/搜索