![](/img/trans.png)
[英]Listing image files in folders and subfolders with PHP and sort them by date created
[英]php scandir sort first single files then folders and subfolders
我的“ / 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
並刪除“空”子文件夾
如果不需要在那里進行其他字母排序,則可以將目錄(而不是遞歸調用)存儲到數組中,並在函數末尾對該數組中的所有元素調用listFolderFiles
。
如果您想使用原始的遞歸方法-不進行文件名排序(如@peter-vančo所述):
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 ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.