php - 使用 PHP 删除空子文件夹

标签 php directory

我正在开发一个 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)) {}
}

根据我的测试,此功能有效,但我很高兴看到任何关于更好地执行代码的想法。

最佳答案

如果您在空文件夹中的空文件夹中有空文件夹,则需要遍历所有文件夹 3 次。所有这一切,因为你首先要广度 - 在测试它的 child 之前测试文件夹。相反,您应该在测试父文件夹是否为空之前进入子文件夹,这样一次就足够了。

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);
}

为了检查隐藏文件,我更新了返回语句行

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

关于php - 使用 PHP 删除空子文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1833518/

相关文章:

php - 使用 JavaScript 的变量冲突

php - 生成有错误的词(汽车品牌/型号)

list - 如何使用 Get-ChildItem -exclude 排除多个文件夹?

Linux - 目录检查

javascript - 尝试 POST 到 mysql 数据库时 PHP 代码卡在浏览器中(以不同的随机间隔)

php - 在逗号分隔的文件中用引号封装文本

web-applications - JSF:超链接到/webapp 子目录中的网页

java - 通过java在jar文件所在的地方创建一个目录

python - 使用目录 | Python

php - 用PHP计算耗时