dougou8573 2012-08-24 15:40
浏览 118
已采纳

在PHP中按字母顺序排序HTML列表

I have a website that contains a manual with many office precedents. When a user uses the HTML upload script it uploads the precedent to a folder on the server. I use the following script to list out all the files in that specific folder.

<?php  //define the path as relative
  $dir = "./OFFICE PRECEDENTS/Business & Corporate Law"; 
  $webpath ="";  //using the opendir function  
  echo "<ol>";    
  // Open a known directory, and proceed to read its contents   
  if ($dh = opendir($dir)) {     
  while (($file = readdir($dh)) !== false) {   
  if (is_dir($dir.'/'.$file)){}      
  else if ($file == '.'){}      
  else if ($file == '..'){} 
  else if ($file == 'index.php'){}     
  else {      
  echo "<li><a href='https://manual.malicki-law.ca/$dir/$file'>$file</a></li>
";      
  }    
  }       
  closedir($dh);     
  } 
  echo "</ol>";     
  ?>

How can I implement a system to alphabetically sort the list?

  • 写回答

5条回答 默认 最新

  • dqsw7529 2012-08-24 15:49
    关注

    For your specific case: If you use scandir() instead of readdir(), the default order is already in alphabetical order.

    http://php.net/manual/en/function.scandir.php

    The second parameter is:

    sorting_order
    By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.

    So instead of:

     if ($dh = opendir($dir)) {     
       while (($file = readdir($dh)) !== false) {   
           // your code   
        }    
      }       
      closedir($dh);  
    

    Just use something like:

    if ($files = scandir($dir))
    {
        foreach ($files as $file) {
           // your code
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码