1 回答
TA贡献1846条经验 获得超7个赞
这是解决您的问题的一种可能的解决方案。我们使用一个权重数组,其键与餐厅数组中的键和值相匹配,如您的问题所示。请注意,对于距离,我们使用负值,因为您希望更近的餐厅(距离值越小)排名越高。然后,我们可以根据每个权重的评分总和对餐厅数组进行排序:
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
)
)
请注意,$restaurants您问题中的变量不是有效的 PHP 结构;我假设你有一个关联数组。
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报