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应该在第一位。如果有空格的话它按字母顺序移动到底为什么会这样。我怎样才能恢复这个问题。请任何人给我解决方案。
答案 0 :(得分:2)
答案 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);
?>