I've been trying to print out files in a list, getting both files, folders and subfolders. I can get everything out, but I want to display folders first. Is there a way to do this?
My code so far:
function getFiles($path) {
foreach (new DirectoryIterator($path) as $file) {
if($file->isDot()) continue;
if($file->isDir())
echo "<li class='folder'>\n";
else
echo "<li>\n";
echo "<a href='#'>" . $file->getFilename() . "</a>\n";
if ($file->isDir()) {
echo "<ul>\n";
getFiles($file->getPathname());
echo "</ul>\n";
}
echo "</li>\n";
}
}
Hope you can help me out!
Instead of echo
add them to a temporary array. I would create an array name $directories
and an array named $files
you can then loop through those two arrays and echo
.
Something like this:
function getFiles($path) {
$directories = array();
$files = array();
foreach (new DirectoryIterator($path) as $file) {
if ($file->isDot())
continue;
if ($file->isDir())
$directories[] = $file;
else
$files[] = $file;
}
foreach($directories as $file) {
echo "<li class='folder'>\n";
echo "<a href='#'>" . $file->getFilename() . "</a>\n";
echo "<ul>\n";
getFiles($file->getPathname());
echo "</ul>\n";
echo "</li>\n";
}
foreach($files as $file) {
echo "<li>\n";
echo "<a href='#'>" . $file->getFilename() . "</a>\n";
echo "</li>\n";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.