scandir - sort numeric filenames

倖福魔咒の 提交于 2019-12-08 19:39:53

问题


Done some searching, but can't seem to find the exact answer I'm looking for.

I'd like to pull in files with numbered filenames using 'scandir($dir)', but have them sort properly. For example, file names are:

1-something.ext

2-something-else.ext

3-a-third-name.ext

.

.

.

10-another-thing.ext

11-more-names.ext

The problem I'm having is that 10-a-fourth-thing.ext will show before 2-something-else.ext. I'd like to find a better way of solving this issue than introducing leading '0' in front of all file names.

Any thoughts? Thanks.


回答1:


natsort does exactly what you need.

sort with SORT_NUMERIC will also work for filenames that start with numbers, but it will break if there are also names that have no numbers in front (all non-number-prefixed names will be sorted before number-prefixed names, and their order relative to one another will be random instead of alphabetic).




回答2:


You can use sort like this:

sort($arr, SORT_NUMERIC); // asuming $arr is your array



回答3:


If you want to reassign keys (which natsort does not do), use usort() combined with strnatcmp() or strnatcasecmp():

usort($arr, 'strnatcmp'); // Or 'strnatcasecmp' for case insensitive


来源:https://stackoverflow.com/questions/9727781/scandir-sort-numeric-filenames

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