main folder is home
- with subfolders and txt
files - on various levels
I need the list of entire folders tree - and count txt
files inside each of them
This code gives the folders but count is always - 0
I suppose paths to folders
and not only folder names - are required, but can't see - how to get them.
function rscan ($dir) {
$all = array_diff(scandir($dir), [".", ".."]);
foreach ($all as $ff) {
if(is_dir($dir . $ff)){
echo $ff . "\n"; // it works
$arr = glob($ff . "/*.txt");
echo count($arr) . "\n"; // always 0
rscan("$dir$ff/");
}
}
}
rscan("home/");
CodePudding user response:
Line 6
$arr = glob($ff . "/*.txt");
Change to the code below:
$arr = glob($dir.$ff . "/*.txt");
CodePudding user response:
An alternate implementation:
<?php
function glob_recursive($pattern, $flags = 0): Int {
$files = glob($pattern, $flags);
$count = count($files);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$count = glob_recursive($dir.'/'.basename($pattern), $flags);
}
return $count;
}
var_dump(glob_recursive('home/*.txt'));
The output is something like:
int(10)