Count subfolders only 1 level down
Hello, I am using the following code to get the information about folders on a webserver using php. I have a website that has folders for photos, the first level are continents, the next is counries in that continent, then geographical regions in each contry. When I display the contienents, I want to be able to display the number of folders under it, but by only 1 level.
Code:
function getDirInfo($pPath) {
// Defines dir info structure
$info = Array("size"=>"0", "files"=>"0", "dirs"=>"0");
// try to open dir path
if ( $dir = @openDir($pPath) ) {
// try to read file in dir
while ( ($file = readDir($dir)) !== FALSE ) {
// if file is . or .. then skip
if ( $file == "." || $file == ".." )
continue;
// get statistic for file
if ( is_file($pPath."/".$file) ) {
$info["size"] += filesize($pPath."/".$file);
$info["files"] ++;
} else {
// get statistic for dir
$info["dirs"] ++;
// get statistic for their sub dir
$ret = getDirInfo($pPath."/".$file);
// summary result
$info["size"] += $ret["size"];
$info["files"] += $ret["files"];
$info["dirs"] += $ret["dirs"];
}
}
}
return $info;
}
So for example, North America will display "3 subfolders" (US, canada, mexico) but right now it shows over 60 (all the us states, and other regoins in other countries. I would like to count the folders only 1 level down and not every folder no matter how deep it is. Can the code above be changed?
Re: Count subfolders only 1 level down
You could add a couple of extra parameters to the function:
Code:
function getDirInfo($pPath, $maxDepth=false, $depth=0)
$maxDepth stipulates how deep the recursion should go, $depth is the current depth which starts at 0.
Then you just modify the call to getDirInfo within the function:
Code:
if ($maxDepth !== false && ($depth < $maxDepth)) {
$ret = getDirInfo($pPath."/".$file, $maxDepth, ++$depth);
}
When you call the function now, just supply i with the depth:
Code:
getDirInfo('currentFolder', 1);
Re: Count subfolders only 1 level down
You could of course do away with the function completely and traverse the directory manually, as you will only ever want to go as deep as one level.
Re: Count subfolders only 1 level down
Thanks, that works perfectly. I cant do anything manually becuase there will always be folders and ect added and this needs to be dynamic.
Re: Count subfolders only 1 level down
He was talking about writing the directory scan in-place.