我正在查询 instagram api 以返回带有以下代码的 json:
$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
所以我想解码 json
if($response){
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
...
所以现在我想将所述数组的内容重新格式化为特定的 json 格式 (geojson),代码大致如下:
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
)
然后使用 json_encode
将其全部返回到一个漂亮的 json 文件中以缓存在服务器上。
我的问题...是我如何使用上面的代码来循环 json?array/json 的外部结构是静态的,但内部需要更改。
在这种情况下,最好构建一个新的数据结构,而不是内联替换现有的数据结构。
例:
<?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);