zoukankan      html  css  js  c++  java
  • 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>";
    }

    运行结果如下:

    /**
     * @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);
    }
  • 相关阅读:
    种类并查集
    因式分解
    最长递增(不减)子序列
    C++之算法题模板
    线段树
    C++之环境搭建
    C++之vector用法
    逆序数以及右边更小数的个数
    Unity3d之动态连接Mesh Renderer和Collider
    Matlab之字符串处理
  • 原文地址:https://www.cnblogs.com/yang-2018/p/10332197.html
Copyright © 2011-2022 走看看