Reputation: 11466
I am retrieving data via JSON and PHP from a URL. I am having difficulty breaking the object apart and displaying the data. The PHP code seems to be working until I get to the for loops.
$jsonurl = 'http://myweb/api.php';
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output->Monitoring AS $monitoring) {
foreach ($monitoring->Status AS $Status){
echo $Status->Emailed;
echo $Status->Status;
}
Here is my data structure:
object(stdClass)#12 (1)
{ ["Monitoring"]=> array(10) { [0]=> object(stdClass)#13 (14)
{
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[1]=> object(stdClass)#14 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[2]=> object(stdClass)#15 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
[3]=> object(stdClass)#16 (14) {
["Status"]=> string(30) "HTTP/1.1 302 Moved Temporarily"
["Emailed"]=> string(1) "0" }
} }
Upvotes: 0
Views: 270
Reputation: 15311
According to the data structure you put, you only need one foreach loop like:
$jsonurl = 'http://myweb/api.php';
$json = file_get_contents($jsonurl);
$json_output = json_decode($json);
foreach ($json_output->Monitoring AS $Status) {
echo $Status->Emailed;
echo $Status->Status;
}
in the first foreach loop, the value ($monitoring in your code, $Status in mine as I just renamed it) is not another array that you need to loop over. It would contain a std object with Emailed and Status as keys.
Upvotes: 1
Reputation: 10257
At the outset, make sure you turn error reporting on so you can see what exactly is failing.
An improper format passed to json_decode
will just return false. It is one of the limitations of PHP's json handling that they are trying to address in the next release by creating a JSONSerializable
interface. Make sure the return for decode is an instance of stdClass
(or an array if you have passed the option for an associative array), otherwise the loops will never execute at all.
Upvotes: 0
Reputation: 4320
First of all, are you sure your script returns actual JSON string? Did you json_encode it?
Did you compare the 'data structure' of the object before JSON and after decoding? Were there any differences? Maybe it is not at all about the foreach loops and JSON and the problem is instead in your data structure of sorts, which seems to consist of multiple sub-objects.
Alternative is to try and use associative arrays instead of objects in that context by returning json_decode($json,true) and treating it as an array.
Upvotes: 1