简体   繁体   English

如何遍历所有带有特殊文件的子文件夹?

[英]How to traverse all sub-folders with special file in it?

I want to traverse all sub-folders of a particular folder and check whether they have a special file in it otherwise delete the sub-folder. 我想遍历特定文件夹的所有子文件夹,并检查它们中是否有特殊文件,否则请删除该子文件夹。

Take this example (file.txt being the special file here): 以以下示例(file.txt是此处的特殊文件):

  • folder_all folder_all
    • folder1 文件夹1
      • file.txt file.txt的
    • folder2 文件夹2
      • file.txt file.txt的
    • folder3 folder3
      • empty

Because "folder3" doesn't have the file, I'd like to delete it. 因为“ folder3”没有文件,所以我想删除它。
And this is what I want to do. 这就是我想要做的。 Any ideas? 有任何想法吗?

Thank you very much! 非常感谢你!

updated code 更新的代码

You can use the RecursiveDirectoryIterator class: 您可以使用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);
}

?>

Simply iterate over all subfolders of folderall and check if the file folder_all/$subfoldername/file.txt exists. 只需遍历folderall的所有子文件夹,并检查文件folder_all/$subfoldername/file.txt存在。 If not, delete it. 如果没有,请删除它。 That should be one loop. 那应该是一个循环。

API: API:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM