首页 > 解决方案 > php中的sort()如何排列目录结构数组?

问题描述

我正在从官方手册中学习 php,刚刚在数组部分https://www.php.net/manual/en/language.types.array.php上的示例 #13当我在本地 Windows 10 中运行示例代码时使用命令行中的 php localserver 我观察到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,排序的预期行为是什么?

谢谢你。

标签: phparrayssortingdirectoryphp-7

解决方案


您的数组按区分大小写的顺序排序(默认为sort),因此以 开头的条目位于以 .A-Z开头的条目之前a-z。如果你想保留一个不区分大小写的顺序,你可以sortSORT_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
)

3v4l.org 上的演示

请注意,根据您对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
)

3v4l.org 上的演示


推荐阅读