php 使用下划线对文件名进行排序

标签 php arrays sorting

我有一个使用 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方法,看看hereusort你可以实现你的自定义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/

相关文章:

php - 如何使用 AngularJS 或 jQuery 更改 HTML 表格中的文本颜色?

php - 我应该使用 Laravel 的集合形式还是传统的 html 形式?哪个更好?

mysql - 如何找到相似的结果并按相似度排序?

python - 将字符串列表 [ '3' , '1' , '2' ] 转换为排序整数列表 [1, 2, 3]

javascript - 如何解析来自websocket的二进制数据?

php - 文件类型在 PHP 中不起作用

javascript - 将计数值添加到具有相同键值的对象(对象数组)

javascript - 根据对象的一个​​属性对对象数组进行排序

c# - 在不同类的方法中打印数组?

node.js - Redis 同时进行 INCR、SORT 和 TTL?