I'm trying to learn how to use JSON to store and retrieve information and I've followed several tutorials and it just isn't working the way it seems it should. On the php page I have the following code:
<?php
$str_data = file_get_contents("test.json");
$str_decode = json_decode($str_data);
foreach($str_decode as $decoded){
echo "Report Item: " . $decoded->reportItem . "Sentences: " . $decoded-sentences;
}
?>
the JSON file has the following:
[
{
"reportItem": "gender",
"sentences": ["gender1",
"gender2",
"gender"]
},
{
"reportItem": "doctor",
"sentences": ["doctor1",
"doctor2",
"doctor3"]
},
{
"reportItem": "consent",
"sentences": ["consent1",
"consent2",
"consent3"]
}
]
If I echo the str_data after the file_get_contents it displays:
[ { "item": "gender", "sentences": ["gender1", "gender2", "gender"] }, { "item": "doctor", "sentences": ["doctor1", "doctor2", "doctor3"] }, { "item": "consent", "sentences": ["consent1", "consent2", "consent3"] } ]
Then, if I do a print_r on str_decode it displays:
Array ( [0] => stdClass Object ( [item] => gender [sentences] => Array ( [0] => gender1 [1] => gender2 [2] => gender ) ) [1] => stdClass Object ( [item] => doctor [sentences] => Array ( [0] => doctor1 [1] => doctor2 [2] => doctor3 ) ) [2] => stdClass Object ( [item] => consent [sentences] => Array ( [0] => consent1 [1] => consent2 [2] => consent3 ) ) )
However, trying to loop through the array with the foureach loop doesn't generate any output. This doesn't seem like it should be very hard and it seems to work in all the videos I've watched, but I can't get it to work. I would appreciate any help understanding what I'm missing here.