php排序多维数组的字母数字值。

时间:2022-10-28 16:15:37

I'm looking for a custom function that will respect the order of the array and sort it by the 'name' index. 'strcasecmp()' function doesn't understand alphanueric values as humans would read it. It thinks 'Apples 12' is a lesser value than 'Apples 5'. I tried this method but cant find a function to compare alphanumeric value:

我正在寻找一个自定义函数,它将尊重数组的顺序并按“名称”索引排序。“strcasecmp()函数不理解字母数字值,因为人们会读它。它认为“苹果12”的价值要比“苹果5”低。我尝试了这个方法,但是找不到一个函数来比较字母数字的值:

$array = array(
    0 => array(
        'id' => 2,
        'type' => 'Apples',
        'name' => 'Apples 5',
    ),
    1 => array(
        'id' => 3,
        'type' => 'Grapes',
        'name' => 'Apples',
    ),
    2 => array(
        'id' => 4,
        'type' => 'Apples',
        'name' => 'Apples 4',
    ),
    3 => array(
        'id' => 5,
        'type' => 'Grapes',
        'name' => 'Apples 01',
    ),
    4 => array(
        'id' => 6,
        'type' => 'Apples',
        'name' => 'Apples 1',
    ),
    5 => array(
        'id' => 7,
        'type' => 'Grapes',
        'name' => 'Apples 12',
    )
);

uasort($array, function($a, $b) {
    return strcasecmp($a['name'], $b['name']);
});

foreach($array as $single) {
    echo $single['name'].'<br />';
}

Unexpected result from code above:

以上代码的意外结果:

Apples
Apples 01
Apples 1
Apples 12
Apples 4
Apples 5

The result I wanted to achieve:

我想达到的结果是:

Apples
Apples 01
Apples 1
Apples 4
Apples 5
Apples 12

Any ideas?

什么好主意吗?

1 个解决方案

#1


4  

use strnatcasecmp() for natural ordering

使用strnatcasecmp()进行自然排序。

#1


4  

use strnatcasecmp() for natural ordering

使用strnatcasecmp()进行自然排序。