如何使用:: setMaxDepth for RecursiveIteratorIterator?

时间:2012-06-05 21:20:04

标签: php recursion spl

我正在使用此脚本,但我想指定递归函数的最大深度。我不知道如何使用它,我总是得到一个错误。我该如何在这里使用::setMaxDepth

public function countFiles($path)
{ 
global $file_count;
$depth=0;
$ite=new RecursiveDirectoryIterator($path);

$file_count=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) :
    $file_count++;
    $files[] = $filename;
endforeach;

return $file_count;
}

1 个答案:

答案 0 :(得分:7)

您需要在setMaxDepth()的实例上调用RecursiveIteratorIterator。在RecursiveIteratorIterator语句中构造foreach时,这很困难。相反,使用变量来保存它。

$files = new RecursiveIteratorIterator($ite);
$files->setMaxDepth($depth);
foreach ($files as $filename => $cur) {
    $file_count++;
    $files_list[] = $filename;
}

但请注意,此处不需要使用循环(除非您的代码执行了上述示例中已删除的其他内容)。您可以使用iterator_count()获取文件计数。

function countFiles($path)
{
    $depth = 1;
    $ite   = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($ite);
    $files->setMaxDepth($depth);
    return iterator_count($files);
}