How to sort an array of numeric strings which also contain numbers. (natural ordering) in PHP

不羁的心 提交于 2021-02-04 21:44:39

问题


How do you sort an array of strings which also contain numbers.

For example I have used the glob() function to get a list of file names.

By default the array output the files in ascending order but reads each numeric character individually rather than a whole number.

Default output

"C://path/to/file/file.tpl"
"C://path/to/file/file1.tpl"
"C://path/to/file/file11.tpl"
"C://path/to/file/file12.tpl"
....
....
"C://path/to/file/file2.tpl"

Required output

"C://path/to/file/file.tpl"
"C://path/to/file/file1.tpl"
"C://path/to/file/file2.tpl"
...
...
"C://path/to/file/file11.tpl"
"C://path/to/file/file12.tpl"

Is there a PHP function that performs this?

Many thanks


回答1:


Use natsort

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".




回答2:


sort($array, SORT_NATURAL);

or

natsort($array);

Natural sorting.



来源:https://stackoverflow.com/questions/28363762/how-to-sort-an-array-of-numeric-strings-which-also-contain-numbers-natural-ord

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