在我的'/templates'文件夹中有以下文件和文件夹:
/templates/folder/contact.html
/templates/folder/index.html
/templates/folder/search.html
/templates/index.html
/templates/music.html
/templates/path/index.html
/templates/path/test.html
/templates/video.html
现在我想先得到列表排序单个文件,
然后是文件夹和子文件夹,我的意思是:
/index.html
/music.html
/video.html
/folder/contact.html
/folder/index.html
/folder/search.html
/path/index.html
/path/test.html
我正在使用这个代码,但是我不知道如何按照这个顺序对它们进行排序…请帮助
<?php
function listFolderFiles($dir, $parent = ''){
$ffs = scandir($dir);
echo '<ol style="padding:0;">';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'.$parent.'/'.$ff;
if(is_dir($dir.'/'.$ff)){
listFolderFiles($dir.'/'.$ff, $ff );
}
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('templates');
?>
请注意:实际上这段代码一次将子文件夹输出为"空",例如/folder
以及子文件夹内的内容,不带初始斜杠:folder/contact.html
但我需要有一个初始斜杠,如:/folder/contact.html
然后删除"empty"子文件夹
如果您不需要在那里进行另一个字母排序,您可以将目录存储(而不是递归调用)到数组中,并在函数末尾为该数组中的所有元素调用listFolderFiles
。
如果您想坚持使用原始的递归方法-不使用文件名排序(如@peter- van
function listFolderFiles($dir, $parent = '')
{
$ffs = scandir($dir);
$subfolders = array();
echo '<ol style="padding:0;">';
foreach($ffs as $ff)
{
if (!is_dir($dir . '/' . $ff))
{
echo '<li>'.$parent.'/'.$ff . '</li>';
}
else if($ff != '.' && $ff != '..')
{
$subfolders[$ff] = $dir.'/'.$ff;
}
}
foreach($subfolders as $ff => $subfolderDir)
{
listFolderFiles($subfolderDir, '/' . $ff);
}
echo '</ol>';
}
这是一个简单的递归迭代器,它将每个项拆分为:
$MójFolder = __DIR__;
$Pliki = array('Pliki'=>array(), 'Foldery'=>array());
$Foldery = [];
$SkanerKatalogówIPlików = new RecursiveDirectoryIterator($MójFolder, RecursiveDirectoryIterator::SKIP_DOTS);
$SkanujWszystkiePodkatalogi = new RecursiveIteratorIterator($SkanerKatalogówIPlików, RecursiveIteratorIterator::SELF_FIRST);
foreach($SkanujWszystkiePodkatalogi as $WszystkiePlikiIFoldery){
$Ścieżka = str_replace($MójFolder, '', $WszystkiePlikiIFoldery);
if($WszystkiePlikiIFoldery->isDir()){
$Pliki['Foldery'][] = '.' . $Ścieżka .'/';
natcasesort($Pliki['Foldery']);
}elseif($WszystkiePlikiIFoldery->isFile()){
$Pliki['Pliki'][] = $Ścieżka ;
}
}