1

我正在查询 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 的外部结构是静态的,但内部需要改变。

4

1 回答 1

1

在这种情况下,最好构建一个新的数据结构,而不是替换现有的内联数据结构。

例子:

<?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);
于 2012-04-18T04:12:36.440 回答