[英]How does sort() in php arranges directory structure array?
我正在從官方手冊中學習 php,剛剛在數組部分https://www.php.net/manual/en/language.types.array.php上的示例 #13 當我在本地 Windows 10 中運行示例代碼時使用命令行中的 php localserver 我觀察到sort()
實際上對數組進行了sort()
。 我嘗試了以下代碼:
<?php
// fill an array with all items from a directory
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
print_r($files);
sort($files);
print_r($files);
closedir($handle);
?>
我得到的輸出如下:
Array
(
[0] => .
[1] => ..
[2] => .ftpquota
[3] => Ftp fxg710ehhrpx.xml
[4] => index.html
[5] => index.php
[6] => Logo
[7] => myphp
[8] => OnlineSlap.rar
)
Array
(
[0] => .
[1] => ..
[2] => .ftpquota
[3] => Ftp fxg710ehhrpx.xml
[4] => Logo
[5] => OnlineSlap.rar
[6] => index.html
[7] => index.php
[8] => myphp
)
如您所見,在使用sort
之前,數組是按字母順序排列的,但在sort()
,順序變得隨機。
為什么數組unsorted
以及排序的預期行為是什么?
謝謝你。
您的數組按區分大小寫的順序排序( sort
的默認值),因此以AZ
開頭的條目位於以az
開頭的條目之前。 如果您想保留不區分大小寫的順序,可以調用sort
與SORT_FLAG_CASE
標志連同SORT_STRING
以實現:
sort($files, SORT_FLAG_CASE | SORT_STRING);
print_r($files);
輸出
Array
(
[0] => .
[1] => ..
[2] => .ftpquota
[3] => Ftpfxg710ehhrpx.xml
[4] => index.html
[5] => index.php
[6] => Logo
[7] => myphp
[8] => OnlineSlap.rar
)
請注意,根據您對Test2.jpg
和Test10.jpg
等文件名進行排序的要求,您可能希望改用natcasesort
,因為這也將按數字排序。 例如,
$files = array (
0 => 'test2.jpg',
1 => 'Test10.jpg'
);
shuffle($files);
sort($files, SORT_FLAG_CASE | SORT_STRING);
print_r($files);
natcasesort($files);
print_r($files);
輸出:
Array
(
[0] => Test10.jpg
[1] => test2.jpg
)
Array
(
[1] => test2.jpg
[0] => Test10.jpg
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.