douxi2670 2014-01-23 02:25
浏览 77
已采纳

按字母顺序排序选择

I am wondering how to sort select options alphabetically. I was reading on another page where you can jQuery and I completely get the hang of it, I'm just confused a tad bit how I'd use it on the code I use for my selecting.

Here's my selection code:

<select class="form-control" id="rareImage" name="rareImage">
<?php
    if($open = opendir(ROOT .'/resources/images/small_furni')) {
        while(false != ($file = readdir($open))) {
            if($file == '.' || $file == '..') {
                continue;
            }
            echo '<option value="'. $file .'" '. ((isset($rareimage) && $rareimage == $file) ? 'selected' : '') .'>'. $file .'</option>';
        }
    }
?>
</select>

The other page suggested giving it a option value and then using jQuery to sort it. But like I said, I'm kind of confused how I'd go about using it on this code. Basically, the above code outputs a list of images to select from, but they're not in alphabetical order.

Reference I used: http://jsfiddle.net/3YjNR/2/

  • 写回答

1条回答 默认 最新

  • douchun6108 2014-01-23 02:52
    关注

    What i did, is that i put all the values i got from the while loop, into an array. I then sorted the array, and looped through it with a foreach... I think there is a better/faster way to do it, but this is what i got so far.

    <select class="form-control" id="rareImage" name="rareImage">
    <?php
    $arr=array();
    if($open = opendir(ROOT .'/resources/images/small_furni')) {
        while(false != ($file = readdir($open))) {
            if($file == '.' || $file == '..') {
                continue;
            }
            $files[]=$file;
        }
    }
    sort($files);
    foreach($files as $file) echo '<option value="'. $file .'" '. ((isset($rareimage) && $rareimage == $file) ? 'selected' : '') .'>'. $file .'</option>';
    ?>
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?