this function recurrsively goes to a particular depth and stops after the depth is reached.
function read_path($root = '.', $depth = 1) {
if($depth == 0) {
return;
}
$last_letter = $root[strlen($root)-1];
$root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
$files = array('files'=>array(), 'dirs'=>array());
if ($handle = opendir($root)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $root.$file;
if (is_dir($file)) {
$directory_path = $file.DIRECTORY_SEPARATOR;
$files['dirs'][$directory_path] = NULL;
} elseif (is_file($file)) {
$files['files'][] = $file;
}
}
closedir($handle);
}
$done = [$root=>$files];
foreach ($done[$root]['dirs'] as $key=>$value) {
$done[$root]['dirs'][$key] = $this->read_path($key, $depth-1);
}
return $done[$root];
}