我正在使用此代码获取子目录列表。
<?php
$path = '/www/sites/';
$directory_iterator = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
$iterator = new RecursiveIteratorIterator($directory_iterator,
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach ($iterator as $file => $info) {
if ($info->isDir()) {
echo $file . "\n";
}
}
?>
但它正在给我这样的回报
/www/sites/000/4e7
/www/sites/000/4e7/.
/www/sites/000/4e7/..
/www/sites/000/4e7/mydomains.com
/www/sites/000/4e7/mydomains.com/.
/www/sites/000/4e7/mydomains.com/..
/www/sites/000/4e7/mydomains.com/web
/www/sites/000/4e7/mydomains.com/web/.
/www/sites/000/4e7/mydomains.com/web/..
/www/sites/000/4e7/mydomains.com/web/cgi-bin
/www/sites/000/4e7/mydomains.com/web/cgi-bin/.
/www/sites/000/4e7/mydomains.com/web/cgi-bin/..
/www/sites/000/4e7/mydomains.com/web/Resources
/www/sites/000/4e7/mydomains.com/web/Resources/.
我将根路径指定为/www/sites
我在上面的输出中只需要
/www/sites/000/4e7/mydomains.com
休息对我来说毫无用处。这意味着我只想从指定的路径爬取最多3个子目录。我有成千上万的子目录,这就是为什么我要修改当前代码,因为它花费了太多时间 提前谢谢。
答案 0 :(得分:0)
使用directoryiterator::isdot(),recursiveiteratoriterator::getdepth(),例如:
<?php
$path = '/www/sites/';
$directory_iterator = new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::KEY_AS_PATHNAME);
$iterator = new RecursiveIteratorIterator($directory_iterator,RecursiveIteratorIterator::SELF_FIRST,RecursiveIteratorIterator::CATCH_GET_CHILD);
foreach ($iterator as $file => $info) {
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Restrict to 3 levels only and ignore non-directory and dot files
if ($info->getDepth() >= 3 || !$info->isDir() || $info->isDot())
continue;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
echo $file . "\n";
}
输出
/www/sites/000
/www/sites/000/4e7
/www/sites/000/4e7/mydomains.com