在列出文件RecursiveIterator时使用ignore数组

时间:2013-01-16 12:50:03

标签: php recursion iterator

我正在使用此函数以递归方式获取文件列表,并且它可以正常工作。

但是,如何修改它以忽略$ignore数组中定义的文件和文件夹?

  function directoryScan($path = 'files', $onlyfiles = true, $fullpath = false)
  {
    $dir = '';
    $ignore = array('.','..','cgi-bin','.DS_STORE','thumb.db','.gitignore', 'folder_to_be_ignored');

    if (isset($path) && is_readable($path))
    {
      $dlist = Array();
      $dir = realpath($path);

      if ($onlyfiles)
      {
        $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
      }
      else
      {
        $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST);
      }

      foreach($objects as $entry => $object)
      {
        if (!$fullpath)
        {
          $entry = str_replace($dir, '', $entry);
          $entry = $path . $entry;
        }

        $dlist[] = $entry;
      }

      vdebug($dlist);
      return $dlist;
    }
  }

1 个答案:

答案 0 :(得分:0)

  foreach($objects as $entry => $object)
  {
    if (!in_array($entry, $ignore)
    {
      if (!$fullpath)
      {
        $entry = str_replace($dir, '', $entry);
        $entry = $path . $entry;
      }

      $dlist[] = $entry;
    }
  }