我有一个使用 DirectoryIterator 获取的文件名数组。我正在尝试对文件名进行排序,以便它们按顺序排列,这就是它们出现在服务器上的方式。
2DAYSALEGATE_PG1.jpg 2DAYSALEGATE_PG2.jpg 722_PG1.jpg PW_PG2_COKE_A.jpg PW_PG3_COKE_A.jpg PWBY4_DELI-1.jpg
When aquiring the file names they are coming out like this. I have tried to use a sort, natsort and natcasesort. The filename the underscore character is considered after the letters. What can I do to get the underscore to sorted as a priority character.
array(6) {
[0]=>
string(20) "2DAYSALEGATE_PG1.jpg"
[1]=>
string(20) "2DAYSALEGATE_PG2.jpg"
[2]=>
string(11) "722_PG1.jpg"
[5]=>
string(16) "PWBY4_DELI-1.jpg"
[3]=>
string(17) "PW_PG2_COKE_A.jpg"
[4]=>
string(17) "PW_PG3_COKE_A.jpg"
}
谢谢
最佳答案
您可以使用 php usort
方法,看看here
与 usort
你可以实现你的自定义compare to
函数并根据它对数组进行排序。
自定义 compare to
函数是int callback ( mixed $a, mixed $b )
,如果 $a < $b
则应返回小于 0 的值, 如果相等则为零,当 $a > $b
时大于 0
使用此方法实现您喜欢的排序顺序
示例:
function cmp($a, $b) {
$aTemp = str_replace('_', '0', $a);
$bTemp = str_replace('_', '0', $b);
return strcmp($aTemp,$bTemp);
}
usort($arr, "cmp");
关于php 使用下划线对文件名进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21416765/