PHP按数组项排序

时间:2012-07-25 11:49:36

标签: php arrays

我有这个数组:

    Array
(
    [0] => stdClass Object
        (
            [ID] => 1206
            [post_title] => Corporation 5
            [zip_code] => 33017
            [miles] => 13.24
        )

    [1] => stdClass Object
        (
            [ID] => 1197
            [post_title] => Contract deal
            [zip_code] => 33432
            [miles] => 22.7
        )

    [2] => stdClass Object
        (
            [ID] => 1057
            [post_title] => Corporation Deal test1
            [zip_code] => 33019
            [miles] => 0
        )

    [3] => stdClass Object
        (
            [ID] => 1040
            [post_title] => Bankruptcy Deal1 test lorem ipsum
            [zip_code] => 33019
            [miles] => 0
        )

    [4] => stdClass Object
        (
            [ID] => 993
            [post_title] => Finally an Affordable Living Trust, Only $100!
            [zip_code] => 33019
            [miles] => 0
        )

)

我希望结果按“英里”排序。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

您可以使用usort功能

function Compare($a, $b) { return $a->miles < $b->miles; }
usort($results, 'Compare');

答案 1 :(得分:1)

public function subval_sort($a, $subkey) {       
    foreach($a as $k=>$v) {
    $b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
    $c[] = $a[$key];
}

return $c;
}

通过数组子值对数组进行排序的函数。 $ a是传递的数组,$ subkey是数组键,它将被排序。