PHP - 用数字对文件名数组进行排序? [英] PHP - sorting an array of filenames with numbers?

查看:77
本文介绍了PHP - 用数字对文件名数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我如何对包含以数字开头的文件名的数组进行排序?因为以 11、12、13 等开头的字符串被认为小于 2,所以我的结果是这样的:

<前>[0] "1.文件一.pdf"[1] 《11.文件十一.pdf》[2] 《12.文件十二.pdf》[3] 《2.文件二.pdf》[4] 《3.文件三.pdf》

我能做些什么来正确排序这些吗?

解决方案

您可以使用 natsort.或 natcasesort,不区分大小写.如果有多个数字(即变音符号),您应该确保使用正确的locale.

如果还不够,即.您还想对数字文字进行排序(一"、二"、三"),您可以使用 usort,这允许使用您的自定义回调作为比较函数.

Can anyone tell me how to sort an array containing filenames that start with numbers? Because strings that start with 11, 12, 13 etc are considered lower than 2, it's scewing my results like this:

[0] "1. File one.pdf"
[1] "11. File eleven.pdf"
[2] "12. File twelve.pdf"
[3] "2. File two.pdf"
[4] "3. File three.pdf"

Is there anything I can do to sort these properly?

解决方案

You can use natsort. or natcasesort, which is case insensitive. If there is more than numbers (ie. diacritics), you should assure that you use proper locale.

If it is not enough, ie. you want also sort number literals ("one", "two", "three"), you can use usort, which permits to use your custom callback as comparison function.

这篇关于PHP - 用数字对文件名数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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