与usort的轻微问题

时间:2013-12-16 16:47:26

标签: php arrays sorting multidimensional-array usort

Distance正确地将我的数组转移到sory时遇到轻微问题。我虽然使用usort可以解决这个问题,但我显然错了?

usort

usort($return, function($a, $b){
    $t1 = $a['Distance'];
    $t2 = $b['Distance'];
    return $t1 - $t2;
}); 

$return产生:

Array
(
[0] => Array
    (
        [ZipCode] => 06096
        [Distance] => 0
    )

[1] => Array
    (
        [ZipCode] => 06096
        [Distance] => 0
    )

[2] => Array
    (
        [ZipCode] => 06026
        [Distance] => 3.16
    )

[3] => Array
    (
        [ZipCode] => 06080
        [Distance] => 4.14
    )

[4] => Array
    (
        [ZipCode] => 06080
        [Distance] => 4.14
    )

[5] => Array
    (
        [ZipCode] => 06078
        [Distance] => 4.14
    )

[6] => Array
    (
        [ZipCode] => 06064
        [Distance] => 3.6
    )

[7] => Array
    (
        [ZipCode] => 06028
        [Distance] => 3.6
    )

[8] => Array
    (
        [ZipCode] => 06028
        [Distance] => 3.6
    )

[9] => Array
    (
        [ZipCode] => 06006
        [Distance] => 4.83
    )

[10] => Array
    (
        [ZipCode] => 06095
        [Distance] => 4.83
    )

[11] => Array
    (
        [ZipCode] => 06095
        [Distance] => 4.83
    )

[12] => Array
    (
        [ZipCode] => 06006
        [Distance] => 4.83
    )

)

1 个答案:

答案 0 :(得分:2)

您在距离上使用strtotime的原因是什么?

这应该有效:

usort($return, function($a, $b){
    return $a['Distance'] - $b['Distance'];
}); 

修改

好的,我看到了问题所在,如the doc所示:

  

从比较函数返回非整数值(例如float)将导致内部强制转换为回调返回值的整数。因此,诸如0.99和0.1之类的值都将被转换为整数值0,这将将这些值比较为相等。

所以解决方法是确保比较函数始终返回一个整数:

usort($return, function($a, $b){
    $t1 = $a['Distance'];
    $t2 = $b['Distance'];
    if ($t1 == $t2) return 0;
    return $t1 < $t2 ? -1 : 1;
});