php 按数字优先或按字母顺序高级排序

php advanced sorting by numbers first & aphabet next

我有一个元素数组,我想先按数字排序,再按字母排序: 从下图中可以看出,一些字符串包含数值,例如(12 英寸、10 英寸等)。 我要的是:6寸,8寸,9寸,10寸,12寸,Athletic ... Western.

当前的 usort 算法如下所示:

usort($facets['style'], function ($a, $b)  {                
            return (intval($a['value']) < intval($b['value'])) ? 1 : strcmp($a['value'], $b['value']);                              
});

谢谢!

我想你正在寻找 strnatcmp or natsort

$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
)

使用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