I'm querying the instagram api to return json with this code:
$instagramClientID = '9110e8c268384cb79901a96e3a16f588';
$api = 'https://api.instagram.com/v1/tags/zipcar/media/recent?client_id='.$instagramClientID; //api request (edit this to reflect tags)
$response = get_curl($api); //change request path to pull different photos
So I want to decode the json
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
...
So now I want to reformat the contents of said array into a particular json format (geojson) the code would be roughly this:
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
And then use json_encode
to return it all into a nice json file to cache on the server.
My question...is how to I use the code above to loop through the json? The outer structure of the array/json is static but the interior needs to change.
In this case it's better to build a new data structure instead of replacing the existing one inline.
Example:
<?php
$instagrams = json_decode($response)->data;
$features = array();
foreach ( $instagrams as $instagram ) {
if ( !$instagram->location ) {
// Images aren't required to have a location and this one doesn't have one
// Now what?
continue; // Skip?
}
$features[] = array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(
$instagram->location->longitude,
$instagram->location->latitude
),
'type' => 'Point'
),
'properties' => array(
'longitude' => $instagram->location->longitude,
'latitude' => $instagram->location->latitude,
// Don't know where title comes from
'title' => null,
'user' => $instagram->user->username,
// No idea where id comes from since instagram's id seems to belong in instagram_id
'id' => null,
'image' => $instagram->images->standard_resolution->url,
// Assuming description maps to caption
'description' => $instagram->caption ? $instagram->caption->text : null,
'instagram_id' => $instagram->id,
)
);
}
$results = array(
'type' => 'FeatureCollection',
'features' => $features,
);
print_r($results);