我想按'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)
的可能重複[PHP - 多uasort功能中斷排序(http://stackoverflow.com/questions/5198276/php-multiple-uasort-functions-breaks-sorting ) – Jon
確實存在很多問題的重複,但上面提供了一個交鑰匙解決方案(我知道是因爲它是我的)。 – Jon
所以你只需要改變$ a [「hits」]> $ b [「hits」]; 返回$ a [「hits」]> $ b [「hits」]; – Waygood