2012-04-18 45 views
1

我查詢Instagram的API來使用此代碼返回JSON:用PHP基本的循環構建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?數組/ json的外部結構是靜態的,但內部需要更改。

+0

什麼是你的輸入和預期的輸出? – six8 2012-04-18 00:37:46

+0

輸入將會是標準的instagram json return:http://instagr.am/developer/endpoints/tags/#get_tags_media_recent,我會將它重新格式化爲GeoJson,並且看起來非常像這樣:http:// alwaysbecreating。 org/zip.json(re:@Cixate) – 2012-04-18 00:38:57

回答

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); 
+0

我收到很多「致命錯誤:不能使用stdClass類型的對象作爲/home/alwaysbe/public_html/zip-script-4/index.php中的數組」錯誤從這個代碼。我在這裏做錯了什麼? – 2012-04-18 04:32:14

+0

對不起,忘了json_decode如何在PHP中工作。我已經修正了這個例子,並且實際測試了這次。 – six8 2012-04-18 04:40:40

+0

Thanks @Cixate! – 2012-04-18 12:20:39