开发者

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):

Because "folder3" doesn't have the file, I'd like to delete it.

And this is what I want to do. Any ideas?

Thank you very much!


updated code

You can use the RecursiveDirectoryIterator class:

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

?>


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


Simply iterate over all subfolders of folderall and check if the file folder_all/$subfoldername/file.txt exists. If not, delete it. That should be one loop.

API:

  • http://php.net/dir
  • http://php.net/file_exists
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜