PHP - sorting an array of filenames with numbers?

不打扰是莪最后的温柔 提交于 2019-12-17 20:08:30

问题


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?


回答1:


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.




回答2:


Use can get the natural ordering using natsort

See it.



来源:https://stackoverflow.com/questions/4561172/php-sorting-an-array-of-filenames-with-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!