首页 > 解决方案 > 在 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

我遇到的困难部分是找到一种方法让它在订购时忽略目录。我仍然需要文件路径,但我只希望它重新排序只考虑基本名称,而不是整个字符串。

有任何想法吗?谢谢

标签: phparrayssortingalphabetical

解决方案


您可以将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
)

3v4l.org 上的演示


推荐阅读