Calculating Student's Average
Part of the Logic & Flow section of Coddy's PHP journey — lesson 36 of 68.
Challenge
EasyYou will receive two inputs: a JSON object representing the existing student gradebook and a student's name. The gradebook uses student names as keys, with each student having an "id" and "grades" array containing their test scores.
Read both inputs, convert the JSON string to a gradebook array, locate the specified student, calculate their average grade, and print the result rounded to 2 decimal places.
To calculate the average: sum all grades in the student's grades array and divide by the number of grades.
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)
Expected output: The student's average grade rounded to 2 decimal places (example: 85.00)
Try it yourself
<?php
// Read the gradebook JSON string
$gradebookJson = fgets(STDIN);
// Read the student name
$studentName = trim(fgets(STDIN));
// Convert JSON to array
$gradebook = (array)json_decode($gradebookJson, true);
// TODO: Write your code below
// Find the student, calculate their average grade, and round to 2 decimal places
// Output the result
echo $average;
?>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