我正在使用RecursiveIteratorIterator()来探索当前路径的子文件夹,但是通过这种方式探索了所有的树,而我只想要为文件探索我的fodler的直接childern。我怎么能对RecursiveIteratorIterator()说再进一步并停止到当前文件夹的第一个子文件?
在Lauri Lehtinen之后,我试过这个:
$it = new RecursiveDirectoryIterator("$directory");
$it->setMaxDepth(1);
我有PHP 5.2.3,但它告诉我setMaxDepth未定义。
致命错误:调用未定义的方法RecursiveDirectoryIterator :: setMaxDepth()
答案 0 :(得分:5)
使用RecursiveIteratorIterator::setMaxDepth
方法将深度设置为1
(或根据需要设置多个级别):
答案 1 :(得分:0)
正如Lauri所说,将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或更高版本。