dongshou6788 2014-12-08 12:59
浏览 65
已采纳

如何从文件夹中读取/选择文件名时对A - > Z进行排序

This might be very obvious however I cannot seem to solve it.

I have the following option menu :

<select name="Image2" onChange="showImage(this.value)">
    <option value="" selected="selected"></option>
  <?php 
     $dir = "../somefolder";//your path
    $dh  = opendir($dir);
    while (false !== ($filename = readdir($dh))) {
        $files[] = $filename;
  echo "<option value='". $filename . "'>" . $filename . "</option>";  }
    sort($files);
 ?>

</select> 
<div id="image_div"></div> 

<script type="text/javascript">
 function showImage(value)
 {
  var img = "<img src='../somefolder/"+value+"' />";
  document.getElementById('image_div').innerHTML = img;
 }
</script>

Which works fine, but all the files are not sorted a-->z is there a way to do this, I have over 100 files in this folder? Any help Welcome

  • 写回答

1条回答 默认 最新

  • dongnuo2879 2014-12-08 13:02
    关注

    You can do two loops, one to read the filenames, and other to output them.

    Since you have about 100 files, it will not change the response time...

    $dh  = opendir($dir);
    while (false !== ($filename = readdir($dh))) {
            $files[] = $filename;
    }
    sort($files);
    foreach ($files as $filename){
         echo "<option value='". $filename . "'>" . $filename . "</option>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?