【问题标题】:How can I sort this php directory list by name?如何按名称对这个 php 目录列表进行排序?
【发布时间】:2021-05-17 12:16:48
【问题描述】:

所以,只是希望我的 webdrive 文件夹是“可浏览的”,所以我找到了这个脚本来为我做这件事。 问题是,列表没有按名称排序 如何修改代码以按文件名排序?

<?php
$dir_open = opendir('.');

while(false !== ($filename = readdir($dir_open))){
    if($filename != "." && $filename != ".."){
        $link = "<a href='./$filename'> $filename </a><br />";
        echo $link;
    }
}

closedir($dir_open);
?>

【问题讨论】:

    标签: php sorting directory


    【解决方案1】:

    您可以将文件名存储在一个数组中,然后使用sort()对其进行排序

    $files = [];
    $dir_open = opendir('.');
    while(false !== ($filename = readdir($dir_open))){
        if($filename != "." && $filename != ".."){
            $files[] = $filename; // store filename
        }
    }
    closedir($dir_open);
    
    // Then, sort and display
    sort($files);
    
    foreach ($files as $filename) {
        $link = "<a href='./$filename'> $filename </a><br />";
        echo $link;
    }
    

    【讨论】:

    • 非常感谢!如果我想以不同的方式排序(例如,按日期),我该怎么做?
    • 您也可以在数组中存储filemtime() 信息。并使用usort() 进行排序。
    • $files[$filename] = filemtime($filename); 然后asort($files)。有很多方法,但在 cmets 中不容易描述 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2021-07-06
    • 2020-06-09
    • 2015-02-11
    相关资源
    最近更新 更多