Adding a Grade to a Student
Part of the Logic & Flow section of Coddy's PHP journey — lesson 35 of 68.
Challenge
EasyYou will receive three inputs: a JSON object representing the existing student gradebook, a student's name, and a grade to add. The gradebook uses student names as keys, with each student having an "id" and "grades" array. The second input is the student's name, and the third input is the grade to add (as a number).
Read all three inputs, convert the JSON string to a gradebook array, locate the specified student, add the new grade to their grades array, and print the updated gradebook using print_r().
Input format:
- First line: A JSON object representing the existing gradebook (example:
{"Alice":{"id":101,"grades":[85,92,78]},"Bob":{"id":102,"grades":[90,88,95]},"Charlie":{"id":103,"grades":[76,84,89]}}) - Second line: The student's name (example:
Alice) - Third line: The grade to add (example:
88)
Expected output: The updated gradebook array displayed using print_r(), with the new grade added to the specified student's grades array
Try it yourself
<?php
// Read the gradebook JSON string
$gradebookJson = fgets(STDIN);
// Read the student's name
$studentName = trim(fgets(STDIN));
// Read the grade to add
$grade = intval(fgets(STDIN));
// Convert JSON to array
$gradebook = (array)json_decode($gradebookJson, true);
// TODO: Write your code below
// Locate the student and add the new grade to their grades array
// Output the updated gradebook
print_r($gradebook);
?>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 Exercise5Student Gradebook
Project Setup: Data StructureAdding a New StudentAdding a Grade to a StudentCalculating Student's AverageFinding the Top StudentGenerating a Report Card3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting