1 回答

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是解決您的問題的一種可能的解決方案。我們使用一個(gè)權(quán)重?cái)?shù)組,其鍵與餐廳數(shù)組中的鍵和值相匹配,如您的問題所示。請(qǐng)注意,對(duì)于距離,我們使用負(fù)值,因?yàn)槟M牟蛷d(距離值越小)排名越高。然后,我們可以根據(jù)每個(gè)權(quán)重的評(píng)分總和對(duì)餐廳數(shù)組進(jìn)行排序:
function get_rating($restaurant, $weights) {
$rating = 0;
foreach ($weights as $factor => $weight) {
$rating += $weight * $restaurant[$factor];
}
return $rating;
}
$weights = array('distance' => -30, 'likes' => 10);
usort($restaurants, function ($a, $b) use ($weights) {
return get_rating($b, $weights) - get_rating($a, $weights);
});
print_r($restaurants);
輸出:
Array
(
[0] => Array
(
[name] => Macdonalds
[distance] => 2
[likes] => 9
)
[1] => Array
(
[name] => Pizza Hut
[distance] => 9
[likes] => 12
)
[2] => Array
(
[name] => Burger King
[distance] => 14
[likes] => 17
)
[3] => Array
(
[name] => KFC
[distance] => 17
[likes] => 3
)
)
請(qǐng)注意,$restaurants您問題中的變量不是有效的 PHP 結(jié)構(gòu);我假設(shè)你有一個(gè)關(guān)聯(lián)數(shù)組。
- 1 回答
- 0 關(guān)注
- 165 瀏覽
添加回答
舉報(bào)