I have been given a JSON file that I need to parse. I am doing some work for a hotel, and the end goal is to build a table that lists:
Room Number
Adult Content (enabled or disabled)
Room Charges (enabled or disabled)
Status (occupied or unoccupied)
The JSON file, I have no control over. It is given to me, and from there I have to create the layout noted above.
This is an example of the JSON file I am given (it is only part of the file, but you will understand how it works from this sample):
{
"apiVersion" : "0.1",
"data" : {
"roomCount" : 105,
"rooms" : [
{
"room_number" : "104",
"services" : [
{
"adult" : {
"enabled" : true
},
"room_charges" : {
"enabled" : true
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "105",
"services" : [
{
"adult" : {
"enabled" : true
},
"room_charges" : {
"enabled" : false
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "106",
"services" : [
{
"adult" : {
"enabled" : false
},
"room_charges" : {
"enabled" : true
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "107",
"services" : [
{
"adult" : {
"enabled" : false
},
"room_charges" : {
"enabled" : false
}
}
],
"status" : "OCCUPIED"
What I have done thus far:
I have tried to parse the data, and I can get the data to display, however, I am having trouble laying it out exactly the way I need it to look as stated above. Currently, my parse script outputs this:
data
roomCount: 105
rooms
0
room_number: 104
services
0
adult
enabled: 1
room_charges
enabled: 1
status: OCCUPIED
I need it to NOT display the key for the nested array, "Services." What I would like as I said above is for the output to look like this:
Room Number: 104
Adult: Enabled or Disabled (depending on true or false)
Room Charges: Enabled or Disabled (depending on true or false)
Status: OCCUPIED or UNOCCUPIED
And finally, here is the code that I have completed so far:
<?php
$string = file_get_contents("test.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($string, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "<br> $key";
} else {
echo "<br> $key: $val <br>";
}
}
?>
I am looking for some refinement on outputting the data in a cleaner way. If you can help or give me any suggestions/advice I will greatly appreciate it.