0

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 Answer 1

2

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;
}); 
3
  • @o7thWebDesign, it's probably a different issue then, I've just tried this code and it should work. Could you post your complete code including the data?
    – laurent
    Dec 16, 2013 at 18:08
  • I can't give you data. It's the CSV dump from the USPS that I imported into MySQL. And I gave you an example of the return data above. The full code simply returns the array above completely unsorted. Adding in the usort orders it to an extent... just not fully: ctauto.o7th.com/assets/temp.php
    – Kevin
    Dec 16, 2013 at 19:23
  • @o7thWebDesign, ok I see what the problem is, I've updated my answer.
    – laurent
    Dec 16, 2013 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.