问题
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