Slight Issue with usort

40 views Asked by At

Having a slight issue getting my array to sory by Distance properly. I though that using usort would do the trick, but I am apparently mistaken?

usort

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

$return produces:

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

There are 1 answers

3
laurent On BEST ANSWER

Any reason you are using strtotime on distances?

This should work:

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

Edit:

Ok I see what the problem is, as written in the doc:

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

So the solution is to make sure the comparison function always returns an integer:

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