2013-02-25 60 views
0

我有這個數組:如何對以下數組進行排序?

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 

任何想法怎麼能這樣做了什麼?

+0

看一看'usort' - http://php.net/usort – hank 2013-02-25 07:44:35

+0

你想的鑰匙,是按照這個順序呢? 'usort'會對值進行排序,但不是鍵。 – bozdoz 2013-02-25 07:50:35

+0

可能重複的[如何按特定鍵排序多維數組?](http://stackoverflow.com/questions/2804690/how-to-sort-a-multidimensional-array-by-a-certain-key) – deceze 2013-02-25 07:56:51

回答

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); 

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

+0

非常感謝你的工作! – sandip 2013-02-25 08:27:01

+0

@sandip:酷:D – 2013-02-25 08:27:24

2

看看usort函數。

只要定義一個函數(本手冊爲 「CMP」 中)進行排序,並用它作爲回調:

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

然後調用它

usort($my_array_variable,"my_sorting_function"); 
3

使用SET類蛋糕

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