循环多个RecursiveDirectoryIterator

时间:2013-06-13 05:36:31

标签: php iterator

我目前有以下PHP:

$directoryIterator = new RecursiveDirectoryIterator( __DIR__ . '/tests/phpunit/' );

/**
 * @var SplFileInfo $fileInfo
 */
foreach ( new RecursiveIteratorIterator( $directoryIterator ) as $fileInfo ) {
    if ( substr( $fileInfo->getFilename(), -8 ) === 'Test.php' ) {
        $files[] = $fileInfo->getPathname();
    }
}

这将创建一个数组,其中包含以/ tests / phpunit中以Test.php结尾的文件的路径。工作得很好,很好。但是现在我也想在/ tests / integration中注册东西。 (/ tests中有更多东西,所以我不能简单地浏览整个目录。)我可以复制代码,但那是蹩脚的。所以现在我想弄清楚如何循环两个RecursiveDirectoryIterator实例。这样做是否可行?

1 个答案:

答案 0 :(得分:7)

要迭代迭代器,您可以使用AppendIterator class.

$directoryIterator = new RecursiveDirectoryIterator( __DIR__ . '/tests/phpunit/' );
$directoryIterator1 = new RecursiveDirectoryIterator( __DIR__ . '/tests/integration/' );
$iterator = new AppendIterator();
$iterator->append(new RecursiveIteratorIterator( $directoryIterator ));
$iterator->append(new RecursiveIteratorIterator( $directoryIterator1 ));

/**
 * @var SplFileInfo $fileInfo
 */
foreach ($iterator as $fileInfo) {
    if ( substr( $fileInfo->getFilename(), -8 ) === 'Test.php' ) {
        $files[] = $fileInfo->getPathname();
    }
}