问题描述
我有一个数组,其中包含许多文件的完整路径。我需要按字母顺序排列的数组,但仅按文件(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
)