加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

使用PHP删除空子文件夹

发布时间:2020-12-13 22:40:05 所属栏目:PHP教程 来源:网络整理
导读:我正在开发一个 PHP函数,它将以递归方式删除所有不包含从给定绝对路径开始的文件的子文件夹. 这是迄今为止开发的代码: function RemoveEmptySubFolders($starting_from_path) { // Returns true if the folder contains no files function IsEmptyFolder($f
我正在开发一个 PHP函数,它将以递归方式删除所有不包含从给定绝对路径开始的文件的子文件夹.

这是迄今为止开发的代码:

function RemoveEmptySubFolders($starting_from_path) {

    // Returns true if the folder contains no files
    function IsEmptyFolder($folder) {
        return (count(array_diff(glob($folder.DIRECTORY_SEPARATOR."*"),Array(".",".."))) == 0);
    }

    // Cycles thorugh the subfolders of $from_path and
    // returns true if at least one empty folder has been removed
    function DoRemoveEmptyFolders($from_path) {
        if(IsEmptyFolder($from_path)) {
            rmdir($from_path);
            return true;
        }
        else {
            $Dirs = glob($from_path.DIRECTORY_SEPARATOR."*",GLOB_ONLYDIR);
            $ret = false;
            foreach($Dirs as $path) {
                $res = DoRemoveEmptyFolders($path);
                $ret = $ret ? $ret : $res;
            }
            return $ret;
        }
    }

    while (DoRemoveEmptyFolders($starting_from_path)) {}
}

根据我的测试,这个功能可行,但我很高兴看到任何有关更好性能代码的想法.

如果空文件夹中的空文件夹中有空文件夹,则需要在所有文件夹中循环三次.所有这些,因为你先测试文件夹,然后测试它的孩子.相反,你应该在测试父文件是否为空之前进入子文件夹,这样一次传递就足够了.
function RemoveEmptySubFolders($path)
{
  $empty=true;
  foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
  {
     if (is_dir($file))
     {
        if (!RemoveEmptySubFolders($file)) $empty=false;
     }
     else
     {
        $empty=false;
     }
  }
  if ($empty) rmdir($path);
  return $empty;
}

顺便说一句,glob不会返回.和..条目.

更短的版本:

function RemoveEmptySubFolders($path)
{
  $empty=true;
  foreach (glob($path.DIRECTORY_SEPARATOR."*") as $file)
  {
     $empty &= is_dir($file) && RemoveEmptySubFolders($file);
  }
  return $empty && rmdir($path);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读