在递归目录迭代器php中从递归排除文件夹 [英] Exclude folders from recursion in recursive directory iterator php

查看:98
本文介绍了在递归目录迭代器php中从递归排除文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行递归时,我需要从特定目录中排除所有文件和文件夹.到目前为止,我已经有了这段代码:

I need to exclude all files and folders from a certain directories while doing the recursion. I have this code so far :

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($websiteRoot.$file["filepathfromroot"]));
     foreach ($it as $currentfile)
     {
      if (!$it->isDot()&&$it->isFile()&&!in_array($it->getSubPath(), $file["exclude-directories"])) {

        //do something
         }
     }

但是,此子路径仅适用于子项,而不适用于子项的文件和子目录.即对于Foo/bar/hello.php的目录结构.如果将Foo添加到排除列表中,hello.php仍会出现在结果中.

However this subpath will only match for children and and not files and sub directories off the children. i.e For a directory structure of Foo/bar/hello.php. If you add Foo to the exclude list hello.php would still come in the result.

有人对此有解决方案吗?

Does anyone have a solution for this ?

推荐答案

替换:

in_array($it->getSubPath(), $file["exclude-directories"])

类似:

!in_array_beginning_with($it->getSubPath(), $file["exclude-directories"])

然后实现该功能:

function in_array_beginning_with($path, $array) {
  foreach ($array as $begin) {
    if (strncmp($path, $begin, strlen($begin)) == 0) {
      return true;
    }
  }
  return false;
}

但这不是一个很好的方法,因为即使它们很大又很深,您也会递归地进入无用的目录.对于您的情况,我建议您做一个老式的递归函数来读取您的目录:

But that's not a very good way because you will recursivly get into useless directories even if they are very big and deep. In your case, I'll suggest you to do a old-school recursive function to read your directory :

<?php

function directory_reader($dir, array $ignore = array (), array $deeps = array ())
{
    array_push($deeps, $dir);
    $fulldir = implode("/", $deeps) . "/";
    if (is_dir($fulldir))
    {
        if (($dh = opendir($fulldir)) !== false)
        {
            while (($file = readdir($dh)) !== false)
            {
                $fullpath = $fulldir . $file;
                if (in_array($fullpath, $ignore)) {
                    continue ;
                }

                // do something with fullpath
                echo $fullpath . "<br/>";

                if (is_dir($fullpath) && (strcmp($file, '.') != 0) && (strcmp($file, '..') != 0))
                {
                    directory_reader($file, $ignore, $deeps);
                }
            }
            closedir($dh);
        }
    }
    array_pop($deeps);
}

如果您尝试directory_reader(".", array("aDirectoryToIngore")),则根本不会读取它.

If you try directory_reader(".", array("aDirectoryToIngore")), it will not be read at all.

这篇关于在递归目录迭代器php中从递归排除文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆