<?php
$json = '[
{name: "KFC", distance: 17, likes: 3},
{name: "Macdonalds", distance: 2, likes: 9},
{name: "Pizza Hut", distance: 9, likes: 12},
{name: "Burger King", distance: 14, likes: 17}
]';
$json = preg_replace('/(\w+)(?=:)/', '"$1"', $json);
$restaurants = json_decode($json, true);
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);
preferences:
25.39 ms | 407 KiB | 5 Q