【问题标题】:How to sort an array of numeric strings which also contain numbers. (natural ordering) in PHP如何对也包含数字的数字字符串数组进行排序。 PHP 中的(自然排序)
【发布时间】:2015-04-06 11:26:34
【问题描述】:

如何对也包含数字的字符串数组进行排序。

例如,我使用 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 函数?

非常感谢

【问题讨论】:

  • 我知道这个问题很简单,但对于那些不知道“自然排序”一词的人来说,答案并不容易找到。

标签: php arrays sorting glob


【解决方案1】:

使用natsort

此函数实现了一种排序算法,该算法以人类的方式对字母数字字符串进行排序,同时保持键/值关联。这被描述为“自然排序”。

【讨论】:

  • 非常感谢。你的答案很完美。
【解决方案2】:

sort($array, SORT_NATURAL);

natsort($array);

自然排序。

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2019-05-26
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多