从目录中排序文件夹名称使用PHP

时间:2016-11-07 08:17:08

标签: php sorting

Hii Everyone,

        Here I get all files from folder and sort names using PHP.


<?php 
$dir = "Car_Brands";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
sort($files);
print_r($files);
?>

按顺序给出结果

    Array ( [0] => . [1] => .. [2] => ALTO [3] => BEAT [4] => CRUZE [5] => Civic mugen kit [6] => Civic type R kit [7] => Ertiga [8] => FIESTA [9] => FIGO [10] => I20 [11] => LANCER [12] => LINEA [13] => MANZA [14] => NEW I20 [15] => New Beat [16] => New Figo [17] => POLO [18] => SWIFT [19] => SX4 [20] => VENTO [21] => VERNA [22] => VISTA [23] => accord car modification [24] => civic customized kit [25] => hondacity [26] => hondacity 2nd generation [27] => hondacity 3rd generation [28] => octavia [29] => rapid )

但我希望ALTO中的Order和Accord应该在第一位。如果有空格的话它按字母顺序移动到底为什么会这样。我怎样才能恢复这个问题。请任何人给我解决方案。

2 个答案:

答案 0 :(得分:2)

他们不断前进,不是因为空间。因为sort区分大小写。

尝试natcasesort

natcasesort($files);

我希望这会对你有所帮助。

答案 1 :(得分:1)

使用natsort()代替sort:

解释:

  

sort()natsort()

之间的差异
<?php
$temp_files = array("temp15.txt","temp10.txt",
"temp1.txt","temp22.txt","temp2.txt");

sort($temp_files);
echo "Standard sorting: ";
print_r($temp_files);
echo "<br>";

natsort($temp_files);
echo "Natural order: ";
print_r($temp_files);
?>
  

输出将是:

Standard sorting: Array ( [0] => temp1.txt [1] => temp10.txt [2] => temp15.txt [3] => temp2.txt [4] => temp22.txt )
Natural order: Array ( [0] => temp1.txt [3] => temp2.txt [1] => temp10.txt [2] => temp15.txt [4] => temp22.txt )

对于您的代码,它将是:

<?php 
$dir = "Car_Brands";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
natsort($files);
print_r($files);
?>