zoukankan      html  css  js  c++  java
  • 递归遍历目录及删除文件

    实例: 递归遍历所有目录及子目录和文件

    <?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;
    }
  • 相关阅读:
    Redis string
    java 是 传值还是传址 Pass-by-value or Pass-by-reference
    IDEA 适用技巧
    测试 MD
    pyqt5 学习总结
    win10 安装anaconda 无法使用pip 报错缺少SSL模块
    Hadoop datanode无法启动
    Ansible 安装jdk
    java 安装后 不能 java javac 说找不到命令 -bash: javac: command not found
    如何去掉MapReduce输出的默认分隔符
  • 原文地址:https://www.cnblogs.com/liuqun/p/12655241.html
Copyright © 2011-2022 走看看