Вопрос

I'm using this script but I would like to specify a max depth to the recursive function. I don't know how to use it, I always get an error. How should I use the ::setMaxDepth here?

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;
}
Это было полезно?

Решение

You need to call setMaxDepth() on an instance of RecursiveIteratorIterator. This is difficult when you construct the RecursiveIteratorIterator within the foreach statement. Instead, use a variable to hold it.

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

However note that the use of a loop is not required here (unless your code does other things that you have removed in the example above). You can get the count of files with 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);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top