In: Computer Science
I need some information on how to show the code to create a JSON data structure with food, calories, fat, protein. while using PHP.
as well as be able to add an additional value through a text box if possible. The program only needs to read the json data in program and show output in the console
I would like the data to be shown in a table once its been compiled.
PHP Program to show JSON Data and update JSON Data.
please refer to the screenshot of the code to understand code indentation.
<?php
/*
$json is a json data we have
*/
$json = '[{"food":"Food 1","calories":"54","fat":"45","protein":"54"},
{"food":"Food 2","calories":"65","fat":"66","protein":"5"},
{"food":"Food 3","calories":"56","fat":"0","protein":"0"}]';
/*
Following code line print each data present in $json
*/
//First decode json data so that it can be converted to associative array
$decoded_json = json_decode($json,true);
echo "Original Record<br>";
for($i=0;$i<sizeof($decoded_json);$i++) {
echo "Displaying record: ".($i+1)."<br><br>";
echo "Food is :".$decoded_json[$i]['food']."<br>"; //Getting value of food key at index $i
echo "Calories :".$decoded_json[$i]['calories']."<br>"; //Getting value of calories key at index $i
echo "Fat : ".$decoded_json[$i]['fat']."<br>"; //Getting value of fat key at index $i
echo "Protein : ".$decoded_json[$i]['protein']."<br>"; //Getting value of protein key at index $i
}
/*
Adding record to JSON.
*/
/*
Create a new array element and add key value
here key will be same as json key and value will be any of your choice
make sure to create same keys as in json element.
*/
$new_record = array();
$new_record['food'] = "Food 4";
$new_record['calories'] = "Food 4";
$new_record['fat'] = "Food 4";
$new_record['protein'] = "Food 4";
/*
append json with newly created associative array using array_push()
*/
array_push($decoded_json,$new_record);
/*
Print new json record.
*/
echo "<br>After Adding 1 element<br><br>";
for($i=0;$i<sizeof($decoded_json);$i++) {
echo "Displaying record: ".($i+1)."<br><br>";
echo "Food is :".$decoded_json[$i]['food']."<br>"; //Getting value of food key at index $i
echo "Calories :".$decoded_json[$i]['calories']."<br>"; //Getting value of calories key at index $i
echo "Fat : ".$decoded_json[$i]['fat']."<br>"; //Getting value of fat key at index $i
echo "Protein : ".$decoded_json[$i]['protein']."<br>"; //Getting value of protein key at index $i
}
?>
Screenshot of code:
Sample Output: