Recap: Leaderboard Sorting
Part of the Logic & Flow section of Coddy's PHP journey — lesson 26 of 68.
Challenge
EasyYou 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
ascordesc
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
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting