如何使用SPL检索完整目录树? [英] How can I retrieve the full directory tree using SPL?
问题描述
如何使用SPL
(可能使用RecursiveDirectoryIterator
和RecursiveIteratorIterator
)检索完整目录树?
How can I retrieve the full directory tree using SPL
, possibly using RecursiveDirectoryIterator
and RecursiveIteratorIterator
?
推荐答案
默认情况下,RecursiveIteratorIterator
将使用LEAVES_ONLY
作为
By default, the RecursiveIteratorIterator
will use LEAVES_ONLY
for the second argument to __construct
. This means it will return files only. If you want to include files and directories (at least that's what I'd consider a full directory tree), you'd have to do:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
,然后可以在其上foreach
.如果要返回目录树而不是输出目录树,则可以将其存储在数组中,例如
and then you can foreach
over it. If you want to return the directory tree instead of outputting it, you can store it in an array, e.g.
foreach ($iterator as $fileObject) {
$files[] = $fileObject;
// or if you only want the filenames
$files[] = $fileObject->getPathname();
}
您还可以通过执行以下操作来创建不包含foreach
的$fileObjects
数组:
You can also create the array of $fileObjects
without the foreach
by doing:
$files[] = iterator_to_array($iterator);
如果只希望返回目录,请像这样在$iterator
上通过foreach
If you only want directories returned, foreach
over the $iterator
like this:
foreach ($iterator as $fileObject) {
if ($fileObject->isDir()) {
$files[] = $fileObject;
}
}
这篇关于如何使用SPL检索完整目录树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!