Menu
Coddy logo textTech

Recap: Leaderboard Sorting

Part of the Logic & Flow section of Coddy's PHP journey — lesson 26 of 68.

challenge icon

Challenge

Easy

You will receive two inputs: first, an associative array of player names and their scores in JSON format, and second, a sorting order (either "asc" or "desc"). Read both inputs, convert the JSON string to an array, sort the leaderboard by scores according to the specified order, and print each player's name and score on a separate line in the format: Name: Score

Use asort() for ascending order and arsort() for descending order to maintain the player name associations with their scores.

Input format:

  • First line: JSON object with player names as keys and scores as values (example: {"Alice":1500,"Bob":2300,"Charlie":1800,"Diana":2100})
  • Second line: Sorting order - either asc or desc

Expected output: Each player's name and score on a separate line in the format Name: Score, sorted according to the specified order

Try it yourself

<?php
// Read the JSON input
$jsonInput = fgets(STDIN);
$leaderboard = (array)json_decode($jsonInput, true);

// Read the sorting order
$order = trim(fgets(STDIN));

// TODO: Write your code below to sort the leaderboard based on the order


// Output each player's name and score
foreach ($leaderboard as $name => $score) {
    echo "$name: $score\n";
}
?>

All lessons in Logic & Flow