Adding a New Student
Part of the Logic & Flow section of Coddy's PHP journey — lesson 34 of 68.
Challenge
EasyYou will receive two inputs: a JSON object representing the existing student gradebook and a new student's information. The gradebook uses student names as keys, with each student having an "id" and "grades" array. The second input contains the new student's data in the format: name,id (example: Diana,104).
Read both inputs, convert the JSON string to a gradebook array, parse the new student information, add the new student to the gradebook with an empty 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]}}) - Second line: New student information in the format
name,id(example:Diana,104)
Expected output: The updated gradebook array displayed using print_r(), with the new student added with an empty grades array
Try it yourself
<?php
// Read the gradebook JSON input
$gradebookJson = fgets(STDIN);
$gradebook = (array)json_decode($gradebookJson, true);
// Read the new student information
$newStudentInfo = trim(fgets(STDIN));
// TODO: Write your code below
// Parse the new student information and add them to the gradebook with an empty 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