【问题标题】:ordering a list of files in a folder using php使用 php 对文件夹中的文件列表进行排序
【发布时间】:2010-09-20 14:19:42
【问题描述】:

我正在使用下面的代码在下拉菜单中显示目录中的所有文件。有谁知道如何使这个按字母顺序排列?我认为它与排序功能有关,我只是不知道如何!

<?php
$dirname = "images/";
$images = scandir($dirname);
$dh = opendir($dirname);

while ($file = readdir($dh)) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
closedir($dh);
?>

【问题讨论】:

    标签: php sorting


    【解决方案1】:

    为什么要使用 scandir() 读取所有文件名,然后使用 readdir() 方法遍历它们?你可以这样做:

    <?php
    
    $dirname = "images/";
    $images = scandir($dirname);
    
    // This is how you sort an array, see http://php.net/sort
    sort($images);
    
    // There's no need to use a directory handler, just loop through your $images array.
    foreach ($images as $file) {
        if (substr($file, -4) == ".gif") {
            print "<option value='$file'>$file</option>\n"; }
        }
    }
    
    ?>
    

    您可能还想使用natsort(),它的工作方式与sort() 相同,但按“自然顺序”排序。 (而不是排序为1,10,2,20,它将排序为1,2,10,20。)

    【讨论】:

      【解决方案2】:

      scandir

      array scandir ( string $directory [, int $sorting_order [, resource $context ]] )
      

      返回一个文件数组和 目录中的目录。 参数

      directory 目录 扫描。

      排序顺序 默认情况下,排序顺序是按字母升序排列。如果 使用了可选的排序顺序 (设置为 1),则排序顺序为 按字母降序排列。

      【讨论】:

        【解决方案3】:
        $matches = glob("*.gif");
        if ( is_array ( $matches ) ) {
           sort($matches);
           foreach ( $matches as $filename) {
              echo '<option value="'.$filename.'">.$filename . "</option>";
           }
        }
        

        【讨论】:

          【解决方案4】:

          正如William Macdonald 指出的here scandir() 实际上将根据其$sorting_order 参数对返回的数组进行排序(或其默认值:“默认情况下,排序顺序是按字母升序排列的。”)。您的代码的问题是,您使用 $images = scandir($dirname); 在您的目录中生成文件数组,但您不再在代码中使用返回的数组。相反,您使用另一种方法迭代目录内容:

          $dh = opendir($dirname);
          while ($file = readdir($dh)) {
              if (substr($file, -4) == ".gif") {
                  print "<option value='$file'>$file</option>\n"; 
              }
          }
          closedir($dh);
          

          这就是您的结果未排序的原因。

          【讨论】:

            猜你喜欢
            • 2013-02-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-03
            • 1970-01-01
            • 1970-01-01
            • 2011-08-25
            • 1970-01-01
            相关资源
            最近更新 更多