Get folders and files recursively from a folder in alphabetical order in PHP?
I need to get all the folders and files from a folder recursively in alphabetical order (folders first, files after)
Is there an implemented PHP function which caters 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 have sorted the array and printed it like so:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
What I need is to know when a new sub directory is found, so I can add some spaces开发者_开发百科 to print it in a directory like structure instead of just a list.
Any help?
Many thanks
Look at the RecursiveDirectoryIterator
.
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure though if it returns the files in alphabetical order.
Edit:
As you say it does not, I think the only way is to sort them yourself.
I would loop through each directory and put directories and files in a seperate arrays, and then sort them, and then recurse in the directories.
I found a link which helped me a lot in what I was trying to achieve:
http://snippets.dzone.com/posts/show/1917
This might help someone else, it creates a list with folders first, files after. When you click on a subfolder, it submits and another page with the folders and files in the partent folder is generated.
精彩评论