PHP的文件名下划线 [英] php sort filenames with an underscore

查看:245
本文介绍了PHP的文件名下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用DirectoryIterator获取的文件名数组.我正在尝试对文件名进行排序,以便它们按照这样的顺序排列,这就是它们在服务器上出现的方式.

I have an array of filenames that I aquire using DirectoryIterator. I am trying to get the filenames to sort so they would be in order like so, this is the way they appear on the server.


    2DAYSALEGATE_PG1.jpg
    2DAYSALEGATE_PG2.jpg
    722_PG1.jpg
    PW_PG2_COKE_A.jpg
    PW_PG3_COKE_A.jpg
    PWBY4_DELI-1.jpg
   

查询文件名时,它们会像这样显示出来.我尝试使用sort,natsort和natcasesort.在字母后面考虑下划线字符的文件名.我该怎么做才能将下划线作为优先字符进行排序.

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方法,将其检出

You can use the php usort method, check it out here with usort you can implement your custom compare to function and sort the array according to it.

自定义compare to函数是int callback ( mixed $a, mixed $b ),如果$a < $b您应该返回小于0的值,如果等于则返回0,而当$a > $b

the custom compare to function is int callback ( mixed $a, mixed $b ) , you should return a value less than 0 if $a < $b , zero if equal and a value bigger than 0 when $a > $b

使用此方法实现您首选的排序顺序

implement your preferred order of sorting using this method

示例:

function cmp($a, $b) {
  $aTemp = str_replace('_', '0', $a);
  $bTemp = str_replace('_', '0', $b);     
  return strcmp($aTemp,$bTemp);
}

 usort($arr, "cmp");

这篇关于PHP的文件名下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆