PHP natsort() 函数
PHP natsort() 函数用"自然排序"算法对数组进行排序,键值保留它们原始的键名
函数原型
natsort( array )
在自然排序算法中,数字 2 小于 数字 10
在计算机排序算法中,10 小于 2,因为 "10" 中的第一个数字小于 2
参数
| 参数 | 描述 |
|---|---|
| array | 必需。规定要进行排序的数组 |
返回值
如果成功则返回 TRUE,如果失败则返回 FALSE
更新日志
| PHP 版本 | 更新说明 |
|---|---|
| PHP 5.2.10 | 当用 0 填充数字字符串时(例如 '00006'),将忽略 0 |
范例
对数组进行排序
<?php $temp_files = array("temp15.txt","temp10.txt","temp1.txt","temp22.txt","temp2.txt"); sort($temp_files); echo "Standard sorting: "; print_r($temp_files); echo "<br>"; natsort($temp_files); echo "Natural order: "; print_r($temp_files);
运行以上 PHP 范例,输出结果如下
Standard sorting:
Array
(
[0] => temp1.txt
[1] => temp10.txt
[2] => temp15.txt
[3] => temp2.txt
[4] => temp22.txt
)
Natural order:
Array
(
[0] => temp1.txt
[3] => temp2.txt
[1] => temp10.txt
[2] => temp15.txt
[4] => temp22.txt
)