按 PHP 中的字母顺序排列包含文件路径的数组
Order an array containing file paths by alphabetical order in 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
, with a callback that compares the 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
)
我有一个包含许多文件的完整路径的数组。我需要按字母顺序排列的数组,但只能按文件的基本名称 (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
, with a callback that compares the 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
)