【问题标题】:How to traverse all sub-folders with special file in it?如何遍历所有包含特殊文件的子文件夹?
【发布时间】:2010-08-02 09:25:32
【问题描述】:

我想遍历特定文件夹的所有子文件夹,并检查其中是否有特殊文件,否则删除子文件夹。

以这个例子为例(file.txt 是这里的特殊文件):

  • folder_all
    • 文件夹 1
      • 文件.txt
    • 文件夹2
      • 文件.txt
    • 文件夹 3

因为“folder3”没有文件,我想删除它。
这就是我想做的。有什么想法吗?

非常感谢!

【问题讨论】:

  • 如果您的子文件夹没有特殊文件,但有其他子文件夹怎么办?还要删吗?
  • 我制定了一个要遵守的规则。如果存在任何特殊文件,所有子文件夹都将被删除。我认为它只是移动二级文件夹,但它们的任何级别。

标签: php directory


【解决方案1】:

更新代码

您可以使用RecursiveDirectoryIterator 类:

<?php

$dir = '/path/';
$file = '/filetosearch.txt';
$paths = array();

$i = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

while($i->valid()) {

    if (!$it->isDot()) {

        $subpath = $it->getSubPath();

        if ($subpath != '') {
            // if inside a subdirectory
            // add the subpath in our array flagging it as false
            if (!array_key_exists($subpath, $paths) $paths[$subpath] = false;

            // check if it's our file
            if (substr_compare($i->getSubPathName(), $file, -strlen($file), strlen($file)) === 0)
                $paths[$subpath] = true;

    }

    $it->next();
}

// now check our paths array and delete all false (not containing the file)
foreach ($paths as $key => $value)
{
    if (!$value) rmdir($dir.$key);
}

?>

【讨论】:

  • 这只是解决方案的一半。那么OP如何知道要删除的文件夹的名称?您的解决方案使用默认的LEAVES_ONLY 作为RecursiveIteratorIterator,因此它甚至不会告诉您文件夹名称。
【解决方案2】:
function recursive_delete_if_exists($path,$file) {
   foreach (glob($path.'/*.*') as $name)
      if (is_dir($name))
         recursive_delete_if_exists($name,$file);
      elseif ($name==$file)
         unlink($path);
}

recursive_delete_if_exists('/folder_all','file.txt');

【讨论】:

    【解决方案3】:

    只需遍历 folderall 的所有子文件夹并检查文件 folder_all/$subfoldername/file.txt 是否存在。如果没有,请删除它。那应该是一个循环。

    API:

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2020-05-03
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多