繁体   English   中英

用PHP基本循环以构建json

[英]Basic looping with php to build 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的外部结构是静态的,但内部需要更改。

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

例:

<?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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM