使用php进行基本循环来构建json

时间:2012-04-18 00:10:56

标签: php json

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

1 个答案:

答案 0 :(得分: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);