2012-07-02 24 views
1

我想按'hits'對數組排序,但我也想查找一個特定的ID並將其設置爲第一次迭代,然後繼續'命中'排序。按x排序php數組然後輸入y

例如,我有一個多維數組:

$myarray = array(
    array(
     "id"=>10, 
     "hits"=>80 
    ), 
    array(
     "id"=>14, 
     "hits"=>50 
    ), 
    array(
     "id"=>15, 
     "hits"=>700 
    ), 
    array(
     "id"=>18, 
     "hits"=>200 
    ) 
); 

我想測試ID是否是什麼特別的事,即如果ID == 18然後把它先,然後排序命中。我如何使用usort和自定義函數來做到這一點?

我想我在尋找類似的東西:

function customsort($a,$b){ 
    if($a["id"]==18){ //or b==18? 
     return -1; 
    } else { 
     return $a["hits"]>$b["hits"]; 
    } 
} 

usort($myarray,"customsort"); 

我想結果是順序爲:

array(
    "id"=>18, 
    "hits"=>200 
), 
array(
    "id"=>14, 
    "hits"=>50 
), 
array(
    "id"=>10, 
    "hits"=>80 
), 
array(
    "id"=>15, 
    "hits"=>700 
) 

(或者,如果他們被打成ABCD然後我需要它是DBAC)

+0

的可能重複[PHP - 多uasort功能中斷排序(http://stackoverflow.com/questions/5198276/php-multiple-uasort-functions-breaks-sorting ) – Jon

+0

確實存在很多問題的重複,但上面提供了一個交鑰匙解決方案(我知道是因爲它是我的)。 – Jon

+0

所以你只需要改變$ a [「hits」]> $ b [「hits」]; 返回$ a [「hits」]> $ b [「hits」]; – Waygood

回答

1

您的代碼中可能會使此不起作用的唯一的事情是return $a["hits"]>$b["hits"];。你的函數應該只返回1/-1(不是真/假),所以把該行改爲:return $a["hits"]>$b["hits"]?1:-1;,它應該按預期工作。

果然,它的工作原理:http://codepad.org/ItyIa7fB

+0

可能要爲$ b添加支票,以防萬一:http://codepad.org/lE4Vs29Y –

+0

哦真棒!謝謝!我不必還要比較$ b [「id」],但我在哪裏發表評論? – Tim

+0

太棒了,非常感謝:) – Tim

相關問題