【问题标题】:Limiting RecursiveIteratorIterator() recursion depth限制 RecursiveIteratorIterator() 递归深度
【发布时间】:2010-06-20 16:32:13
【问题描述】:

我正在使用 RecursiveIteratorIterator() 来探索我当前路径的子文件夹,但是通过这种方式探索所有树,而不是我想要探索我的 fodler 的直接子级的文件。我怎么能对 RecursiveIteratorIterator() 说不要走得太远,停止到当前文件夹的第一个子文件夹?

在 Lauri Lehtinen 之后,我尝试过这个:

    $it = new RecursiveDirectoryIterator("$directory");
    $it->setMaxDepth(1);

我有 PHP 5.2.3,但它告诉我 setMaxDepth 未定义。

致命错误:调用未定义的方法 RecursiveDirectoryIterator::setMaxDepth()

【问题讨论】:

  • 您调用的是 RecursiveDirectoryIterator,而不是 RecursiveIteratorIterator。

标签: php subdirectory


【解决方案1】:

使用RecursiveIteratorIterator::setMaxDepth 方法将深度设置为1(或任意多个级别):

【讨论】:

    【解决方案2】:

    正如劳里所说,将RecursiveIteratorIterator::setMaxDepth 设置为 1 是最好的方法。

    请查看http://www.php.net/manual/en/class.recursiveiteratoriterator.php#91519,了解以下如何使用它的示例:

    <?php
    $directory = "/tmp/";
    $fileSPLObjects =  new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($directory),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
    try {
        foreach( $fileSPLObjects as $fullFileName => $fileSPLObject ) {
            print $fullFileName . " " . $fileSPLObject->getFilename() . "\n";
        }
    }
    catch (UnexpectedValueException $e) {
        printf("Directory [%s] contained a directory we can not recurse into", $directory);
    }
    ?>
    

    如果您遇到问题,请确保您使用的是 PHP 5.1.0 或更高版本。

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 2016-03-02
      • 2011-02-07
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多