RecursiveIterator用于获取子目录的Iterator


RecursiveIteratorIterator to fetch subdirectories

目前我正在通过php处理目录。我可以列出任何给定目录的子目录。然而,结果并不是我想要的100%。下面的代码返回子目录,但除此之外,它还返回数组中的主目录。如何只返回目录的子目录?

$root = '/test';
$iter = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::CATCH_GET_CHILD // Ignore "Permission denied"
);
$paths = array($root);
foreach ($iter as $path => $dir) {
    if ( $dir->isDir() ) {
        $paths[] = $path;
    }
}

电流输出

Array ( [0] => /test [1] => /test/asf8 [2] => /test/some2 [3] => /test/something ) 

所需输出

Array ( [0] => /test/asf8 [1] => /test/some2 [2] => /test/something ) 

我会更改

if ( $dir->isDir() )

if ( $dir->isDir() && $dir != $root)

删除根目录