PHP数组sort / multi_sort usort

时间:2011-05-16 15:41:30

标签: php

我需要按距离对此数组进行排序

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 Pizza
            [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
        )

)

我用过这个..

usort($results, 'sortByOrder');

用这个..

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

但它不起作用

3 个答案:

答案 0 :(得分:3)

您的sortByOrder功能看起来不太正确。

来自usort

  

比较功能必须返回一个   小于,等于或的整数   如果第一个大于零   论证被认为是   分别小于,等于或   大于第二个。

答案 1 :(得分:3)

这应该做的工作:

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

usort ( $results, 'sortByOrder' );

你的代码的问题是比较函数sortByOrder在这里应该返回0如果它们相等,或者如果其中一个更大则返回-1/1。但是你的函数返回了距离的差异,这是usort()无法解析的。

答案 2 :(得分:2)

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