繁体   English   中英

php scandir首先对单个文件进行排序,然后对文件夹和子文件夹进行排序

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM