php - 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
,排序的预期行为是什么?
谢谢你。
解决方案
您的数组按区分大小写的顺序排序(默认为sort
),因此以 开头的条目位于以 .A-Z
开头的条目之前a-z
。如果你想保留一个不区分大小写的顺序,你可以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
)
推荐阅读
- sql - 我想做一个数据验证(如果 A 列值之一与 C 列值之一匹配)
- django - 可以为 Django SQLite3 默认数据库创建 ArrayField 吗?
- heroku - 未找到 Heroku 自定义域 (404)
- angular - 如果我将访问令牌(JWT)存储在 Angular 项目的本地存储中,那有什么问题?
- javascript - 如何在 React TypeScript 中访问嵌套数据接口
- flutter - 如何在 Flutter 中添加 TextEditingController 并从动态 TextFormField 中获取文本值?
- jpa - 事务性不适用于 JPA saveAll
- c - 由于函数 asprintf 无法编译程序
- javascript - 如何将字符串输入到给定位置的数组中?
- c# - 如何使特定的 DataGridTemplate 列单元格只读