如何对也包含数字的数字字符串数组进行排序。 PHP 中的(自然排序)
How to sort an array of numeric strings which also contain numbers. (natural ordering) in PHP
如何对还包含数字的字符串数组进行排序。
例如,我使用了 glob() 函数来获取文件名列表。
默认情况下,数组按升序输出文件,但会单独读取每个数字字符而不是整数。
默认输出
"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"
需要输出
"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"
是否有执行此操作的 PHP 函数?
非常感谢
使用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".
sort($array, SORT_NATURAL);
或
natsort($array);
自然排序。
如何对还包含数字的字符串数组进行排序。
例如,我使用了 glob() 函数来获取文件名列表。
默认情况下,数组按升序输出文件,但会单独读取每个数字字符而不是整数。
默认输出
"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"
需要输出
"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"
是否有执行此操作的 PHP 函数?
非常感谢
使用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".
sort($array, SORT_NATURAL);
或
natsort($array);
自然排序。