php - 在 PHP 中按字母顺序对包含文件路径的数组进行排序
问题描述
我有一个包含许多文件的完整路径的数组。我需要按字母顺序排列的数组,但只能按文件的基本名称(file1.exe)
例如:
/path/2/file3.exe
/path/2/file4.exe
/path/to/file2.exe
/path/to/file1.exe
我希望输出看起来像这样:
/path/to/file1.exe
/path/to/file2.exe
/path/2/file3.exe
/path/2/file4.exe
我遇到的困难部分是找到一种方法让它在订购时忽略目录。我仍然需要文件路径,但我只希望它重新排序只考虑基本名称,而不是整个字符串。
有任何想法吗?谢谢
解决方案
您可以将usort
, 与比较basename
每个文件名的回调一起使用。例如:
$files = array('/path/to/file3.exe',
'/path/to/file4.exe',
'/path/2/file2.exe',
'/path/2/file1.exe'
);
usort($files, function ($a, $b) {
return strcmp(basename($a), basename($b));
});
print_r($files);
输出:
Array
(
[0] => /path/2/file1.exe
[1] => /path/2/file2.exe
[2] => /path/to/file3.exe
[3] => /path/to/file4.exe
)
推荐阅读
- java - Flyway Mutli Schema:如何在迁移脚本sql文件中指定模式名称
- python - 我在 python Beautiful Soup 中得到一个空列表
- highcharts - 如果 x 轴值太小,则内部的 X 范围图表标签不可见
- date - NestJS gRpc:为什么 Nestjs 将日期字符串转换为不同的格式?
- c# - 如何从 SQLite 中选择带小数秒的时间并在 C# 中插入到 SQL Server
- flutter - 指示器选项卡颤动
- javascript - 无法在 vue js 生产中播放视频(Vue Cli 3)
- javascript - 拆分数组并将值加在一起或根据jquery中的多项选择进行减法
- dart - 如何在 Dart 中测试两个持续时间是否大致相等
- javascript - 使用 Javascript 在表单字段中显示最近提交的数据