Get folders and files recursively from a folder in alphabetical order in PHP?
I need to get all folders and files from a folder recursively in alphabetical order (folders first, files after)
Is there a PHP implemented function that is suitable for this?
I have this function:
function dir_tree($dir) {
$path = '';
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..' && $dircont[$i] !== '.svn') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
I sorted the array and printed it like this:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
I need to know when a new subdirectory will be found, so I can add some spaces to print it in a directory like a structure, not just a list.
Any help?
Many thanks
source to share
I found a link that helped me a lot with what I was trying to achieve:
http://snippets.dzone.com/posts/show/1917
It might help someone else, it creates a list with folders first, then files. When you click on the subfolder it submits and another page is created with folders and files in the partent folder.
source to share
Take a look RecursiveDirectoryIterator
.
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure if it will return the files in alphabetical order.
Edit:
As you say they are not, I think the only way is to sort them yourself.
I looped through each directory and put directories and files in separate arrays and then sorted them and then returned them to directories.
source to share