prepare(" SELECT r.id, r.name, ROUND(MEDIAN(b.bewertung)) AS median_score FROM Restaurant r LEFT JOIN Bewertung b ON r.id = b.fk_restaurant_id GROUP BY r.id, r.name ORDER BY median_score DESC NULLS LAST "); $stmt->execute(); $restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC); $tiers = []; foreach ($restaurants as $restaurant) { $score = $restaurant['median_score']; if ($score >= 9) { $tiers['S'][] = $restaurant; } elseif ($score >= 7) { $tiers['A'][] = $restaurant; } elseif ($score >= 5) { $tiers['B'][] = $restaurant; } elseif ($score >= 3) { $tiers['C'][] = $restaurant; } elseif ($score >= 1) { $tiers['D'][] = $restaurant; } else { $tiers['Unrated'][] = $restaurant; // For restaurants with no reviews } } echo json_encode($tiers); ?>