开发者

PHP array sort / multi_sort usort

开发者 https://www.devze.com 2023-03-06 01:31 出处:网络
I need to sort this array by distance Array ( [0] => Array ( [name] => Pyro Pizza [distance] => 2.3

I need to sort this array by distance

Array
(
    [0] => Array
        (
            [name] => Pyro Pizza
            [distance] => 2.3
        )

    [1] => Array
        (
            [name] => Sparky's Pizza
            [distance] => 2.1
        )

    [2] => Array
        (
            [name] => American Dream Pizza - Portland
            [distance] => 0.5
        )

    [3] => Array
        (
            [name] => Ken's Artisan Pi开发者_如何学Czza
            [distance] => 1.1
        )

    [4] => Array
        (
            [name] => Sparky's Pizza - SE
            [distance] => 2.2
        )

    [5] => Array
        (
            [name] => Vincente's Gourmet Pizza and the V-Room
            [distance] => 2
        )

    [6] => Array
        (
            [name] => Blind Onion Pizza and Pub
            [distance] => 0.6
        )

    [7] => Array
        (
            [name] => Hot Lips Pizza
            [distance] => 1.9
        )

    [8] => Array
        (
            [name] => Flying Pie Pizzeria
            [distance] => 2
        )

    [9] => Array
        (
            [name] => Hammy's Pizza
            [distance] => 2.4
        )

)

I used this..

usort($results, 'sortByOrder');

with this..

function sortByOrder($a, $b) {
    return $a['distance'] - $b['distance'];
}

but it doesn't work


This should do the job:

function sortByOrder($a, $b) {
    if ( $a ['distance'] == $b ['distance'] ) return 0;
    return ( $a ['distance'] < $b ['distance'] ) ? -1 : 1;
}

usort ( $results, 'sortByOrder' );

The problem with your code is that the comparison function, sortByOrder here, should return either 0 if they are equal or -1/1 if one of them is bigger. Your function however returned the difference in distance, which usort() can't parse.


Your sortByOrder function doesn't look quite right.

From usort

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.


    function sortByOrder($a, $b) {
        if ($a['distance'] == $b['distance']) return 0; 
        return ($a['distance'] < $b['distance']) ? -1 : 1;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消