我有一个元素数组,我想先按数字排序,然后再按字母排序: 从下面的图像中可以看到,一些字符串包含数字值(例如12英寸,10英寸等)。 我想要的是:6英寸,8英寸,9英寸,10英寸,12英寸,运动……西方。
当前的usort算法如下:
usort($facets['style'], function ($a, $b) {
return (intval($a['value']) < intval($b['value'])) ? 1 : strcmp($a['value'], $b['value']);
});
谢谢!
答案 0 :(得分:1)
使用natsort():
查看其工作原理:
// input
$array = [
'8 Inch',
'6 Inch',
'12 Inch',
'10 Inch',
'Athletic',
'Western',
'9 Inch'
];
natsort($array);
// output
Array
(
[1] => 6 Inch
[0] => 8 Inch
[6] => 9 Inch
[3] => 10 Inch
[2] => 12 Inch
[4] => Athletic
[5] => Western
)
请参见Demo
答案 1 :(得分:0)
$a = [
'a', '12 inch', '10 inch', '5 inch','z','b'
];
$b = $a;
// way 1 (keys are lost)
usort($a, function ($a, $b) {
return (strnatcmp($a,$b));
});
print_r($a);
// way 2 (keys are preserved)
natsort($b);
print_r($b);
结果:
Array
(
[0] => 5 inch
[1] => 10 inch
[2] => 12 inch
[3] => a
[4] => b
[5] => z
)
Array
(
[3] => 5 inch
[2] => 10 inch
[1] => 12 inch
[0] => a
[5] => b
[4] => z
)