如何对以下数组进行排序?

时间:2013-02-25 07:43:04

标签: php arrays cakephp multidimensional-array

我有这个数组:

  Array
(
[0] => Array
    (
        [id] => 6347
        [lat] => 18.520430
        [lng] => 73.856743
        [country_id] => 18
        [description] => pune is vary nice plac!!!!!!!!!!!!<br>
        [loc_badge] => img/icon-monument.png
        [distance] => 0
        [country] => india
        [city] => pune
        [refId] => 6340
        [avgRate] => 4.7
    )

[1] => Array
    (
        [id] => 6587
        [lat] => 18.649632
        [lng] => 73.744843
        [country_id] => 18
        [description] => Ravet is vary nice city near by pune<br>
        [loc_badge] => img/icon-attraction.png
        [distance] => 18.5865663140631
        [country] => india
        [city] => ravet
        [refId] => 6749
        [avgRate] => 0
    )

[2] => Array
    (
        [id] => 6633
        [lat] => 17.691401
        [lng] => 74.000938
        [country_id] => 18
        [description] => satara is vary nice city<br>
        [loc_badge] => img/icon-monument.png
        [distance] => 93.4305849434119
        [country] => india
        [city] => satara
        [refId] => 6834
        [avgRate] => 6
    )

[3] => Array
    (
        [id] => 6213
        [lat] => 18.655491
        [lng] => 72.867920
        [country_id] => 150
        [description] => Alibag  is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.
        [loc_badge] => img/icon-beach.png
        [distance] => 105.287803206408
        [country] => maharashtra
        [city] => alibag
        [refId] => 6212
        [avgRate] => 2
    ) 
)

我想按 avgRate 的降序对此数组进行排序,以便数组索引如下:

2 0 3  1

任何想法如何做到这一点?

3 个答案:

答案 0 :(得分:3)

使用蛋糕中的SET

$result = Set::sort($yourArray, '{n}.avgRate', 'desc');

答案 1 :(得分:2)

查看usort功能。

只需定义一个函数(在手册中作为“cmp”)进行排序并将其用作回调:

function my_sorting_function($a, $b)
{
    return $a["avgRate"]>$b["avgrate"]?1:-1;
}

然后调用它

usort($my_array_variable,"my_sorting_function");

答案 2 :(得分:2)

试试这个:使用array_multisort

$sort = array();
foreach($your_array as $k=>$v) {
    $sort['avgRate'][$k] = $v['avgRate'];
}

array_multisort($sort['avgRate'], SORT_DESC, $your_array);


echo "<pre>";
print_r($your_array);

参考:http://php.net/manual/en/function.array-multisort.php