2012-09-17 32 views
1

我正在嘗試使用PHP來構建一個非常基本的網頁,其中顯示了一個Foursquare用戶的800多個提示與他們的保存和Like計數在HTML表格中的報告和分析目的。以下是我在foursquare上的意思示例:http://foursquare.com/redbull/list/tips。 (再次,redbull只是我的例子..我正在與一個有812個提示的組織合作)。通過使用限制/偏移量的Foursquare API結果來構建表格

四方提供了一個API來獲取這些數據:

https://api.foursquare.com/v2/lists/{USER-ID}/tips?oauth_token={oauth-token}&limit=200&v=20120917 

,但你只能得到200個結果的時間和必須使用的偏移量,以獲得下一個200,400等:

https://api.foursquare.com/v2/lists/{USER-ID}/tips?oauth_token={oauth-token}&limit=200&offset=200&v=20120917 

在我的情況下,我需要調用API 5次才能獲得所有812個提示。我想出了一個非常笨重且不可擴展的解決方案,我多次調用這個API,並不斷在表中創建行。這裏是我的醜陋但工作的解決方案:http://pastebin.com/WL6kdTPY

但顯然,隨着技巧的不斷增長,我將需要不斷修改我的代碼以解釋每次迭代200次以上。在API數據中,我可以看到提示的總提示(812),所以我覺得我應該可以使用它來提出更精益的解決方案。

誰能幫助? 謝謝!

回答

1

第二循環應該做的伎倆:你檢查

<?php 


$today = date("Ymd"); 
$likes = 0; 
$todo = 0; 

$offset = 0; 
$limit = 200; 
do{ 
    $url="https://api.foursquare.com/v2/lists/{user-id}/tips?oauth_token={oauth_token}&limit=".$limit."&offset=".$offset."&v={$today}"; 
    $source = file_get_contents($url); 
    $obj = json_decode($source, true); 
    foreach($obj['response']['list']['listItems']['items'] as $item) 
    { 

     echo "<tr>"; 
     echo "<td style = 'width: 75px;'>" . date('m/d/y', $item['createdAt']) . "</td>" ; 
     echo "<td style = 'width: 200px;'>" . $item['venue']['name'] . "</td>" ;  
     echo "<td style = 'width: 400px;'>" . $item['tip']['text'] . "</td>" ; 
     echo "<td style = 'width: 50px; text-align: center;'>" . $item['tip']['likes']['count'] . "</td>" ; 
     echo "<td style = 'width: 50px; text-align: center;'>" . $item['tip']['todo']['count'] . "</td>" ; 
     echo "</tr>"; 
     $likes += $item['tip']['likes']['count']; 
     $todo += $item['tip']['todo']['count']; 

    } 
    $offset += $limit; 
} while(count($obj['response']['list']['listItems']['items']) >= $limit); 


?> 

Basicly如果退回的項目的數量比爲每個請求的下限。這應該意味着你已經達到了目的

+0

hmm ..在$ offset = 0後面添加了一個分號並將我的用戶標識和令牌替換回了url後,我只獲得了代碼的前200個結果。你的幫助。 –

+0

抱歉寫了我的情況有點快,我需要計數$ obj ['response'] ['list'] ['listItems'] ['items']不是$ item:/ – Kevthunder

+0

不需要道歉。有用。你太棒了! –