【问题标题】:How to sort out files after opening directory打开目录后如何整理文件
【发布时间】:2013-06-05 00:05:54
【问题描述】:

我有这段代码,它从指定目录读取文件,并将内容输出到下拉菜单中。问题是所有文件都没有按字母数字顺序列出。他们都乱七八糟了!无论如何,这是代码:

<form name="index1">
<select name="menu" onchange="jump(this.form)">
<?php

$dir = opendir($dirname);
echo '<option value="">Choose a chapter or volume</option>';
while(false != ($file = readdir($dir)))
{
    if(($file != ".") and ($file != "..") and ($file != "afile.php")){      
        $name = basename($file,".php");
        echo "<option value=".$file.">$name</option>";
    }
}           
?>
</select>
</form>

我做错了什么?

【问题讨论】:

    标签: php sorting directory


    【解决方案1】:

    这可能会解决您的问题:

    <form name="index1">
    <select name="menu" onchange="jump(this.form)">
    <?php
    
        echo '<option value="">Choose a chapter or volume</option>';
    
        // Get an array of files in the "$dirname" path
        // The array should be sorted by name ascending
        $files = array_filter(glob($dirname. '/*'), 'is_file');
    
        foreach ($files as $file) {
            if ($file != "afile.php") {
                $name = basename($file,".php");
                echo "<option value=".$file.">$name</option>";
            }
        }
    
    ?>
    </select>
    </form>
    

    您可以查看glob 功能,非常有用!

    【讨论】:

      【解决方案2】:

      有错别字:

      你写的:

      foreach(files as $file) {
      

      但应该是:

      foreach($files as $file) {
      

      【讨论】:

      • 我知道您是没有评论权限的新用户,但这并不能真正被视为答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多