簡體   English   中英

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

[英]Sort HTML list alphabetically in PHP

我的網站包含許多辦公室先例的手冊。 當用戶使用HTML上載腳本時,它會將先例上載到服務器上的文件夾。 我使用以下腳本列出該特定文件夾中的所有文件。

<?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>\n";      
  }    
  }       
  closedir($dh);     
  } 
  echo "</ol>";     
  ?>

如何實現系統按字母順序對列表進行排序?

我相信這應該對你有所幫助:

natcasesort: http ://www.php.net/manual/en/function.natcasesort.php

usort: http ://www.php.net/manual/en/function.usort.php,帶比較器功能,比較strtolower(a)和strtolower(b)

您需要先創建一個數組。

希望這可以幫助。

對於您的特定情況:如果使用scandir()而不是readdir() ,則默認順序已按字母順序排列。

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

第二個參數是:

sorting_order
默認情況下,排序順序按字母順序升序排列。 如果可選的sorting_order設置為SCANDIR_SORT_DESCENDING,則排序順序按字母順序降序排列。 如果設置為SCANDIR_SORT_NONE,則結果未排序。

所以代替:

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

只需使用以下內容:

if ($files = scandir($dir))
{
    foreach ($files as $file) {
       // your code
    }
}

將其保存到數組中,但是然后使用字母數字鍵而不是數字鍵。 然后,您應該能夠在鍵上使用排序功能,並且您的值會更改為正確的順序。 然后迭代數組並再次回顯它們。

有關排序數組的更多信息: http//php.net/manual/en/array.sorting.php

<?php
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse");

sort($my_array);
print_r($my_array);
?>

或者您可以使用:asort,rsort,arsort

很多方法都是這樣, glob()也很好,那么你不必擔心目錄。

<?php 

$dir = "./OFFICE PRECEDENTS/Business & Corporate Law/";

$files = glob($dir."*.*");
sort($files);//Sort the array

echo "<ol>";
foreach($files as $file){
    if($file == $dir.'index.php'){continue;}
    $file = basename($file);
    echo "\t<li><a href='https://manual.malicki-law.ca/$dir/$file'>$file</a></li>\n";
}
echo "</ol>";
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM