Hello all!
I'm a bit confused on how to use JSON. So far I've been doing fine but now that the format includes arrays I'm hitting a wall.

I'm using weather underground's API to to pull weather data. My file is http://api.wunderground.com/api/658c0f8b283e4b98/tide/q/VA/Norfolk.json
This may help for visualizing if you haven't seen it before
http://jsonformatter.curiousconcept.com/

So if I want tideSite I can normally do:
$json_string = file_get_contents("http://api.wunderground.com/api/658c0f8b283e4b98/tide/q/VA/Norfolk.json");
$tide_parsed_json = json_decode($json_string);

$tide = $tide_parsed_json->{'tide'}->{'tideInfo'}->{'tideSite'};

but that's not working, is there a syntax like {'tideInfo[0]'} that I'm not understanding? Thanks!!

You can try it in XML also, but be aware that your are disaplaying your API key :)

Member Avatar for diafol

json_decode has a flag that allows you to change the contents to an array - this is the 2nd parameter and set it to true:

$tide_parsed_json = json_decode($json_string, true);

You can then check the structure with print_r(). It shouldn't really make a difference, but I find an associative array easier to work with.

I also prefer the associative array, as what Diafol already noted.

If you still prefer to have the object method, you can code it like this... very nice and simple

<?php

$json = file_get_contents('http://api.wunderground.com/api/658c0f8b283e4b98/tide/q/VA/Norfolk.json'); 

$data = json_decode($json);

foreach($data->tide->tideInfo as $item){
echo 'Tide Site :'. $item->tideSite .'<br/>';
echo 'Latitude : '. $item->lat .'<br/>';
echo 'Longtitude : '. $item->lon .'<br/>';
echo 'Units : '.$item->units .'<br/>';
echo 'Type : ' .$item->type .'<br/>';
echo 'Time Zone Name: '. $item->tzname.'<br/>';

}

If properly executed, the codes above should give us something similar to this

Tide Site :Little Creek NAB, Chesapeake Bay, Virginia
Latitude : 36.9117
Longtitude : -76.175
Units : feet
Type : tide
Time Zone Name: America/New_York

Example above will only parse the first item in the Tide array.. I you want to access the second item tideSummary , you will have to elevate the $data->tide having its own array.. something like this..

foreach($data->tide as $items){
## loop through the $item->tideInfo
## loop through all of them until you are getting the result you wanted

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.