简体   繁体   English

PHP-用数字对文件名数组进行排序?

[英]PHP - sorting an array of filenames with numbers?

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: 因为以11、12、13等开头的字符串被认为小于2,所以我的结果像这样:

[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 . 您可以使用natsort or natcasesort , which is case insensitive. natcasesort ,不区分大小写。 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. 您还希望对数字文字进行排序(“一个”,“两个”,“三个”),则可以使用usort ,它可以将自定义回调用作比较函数。

Use can get the natural ordering using natsort 使用可以使用natsort获得自然排序

See it. 看见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM