Reputation: 609
I am trying to build a very basic web page using PHP that displays a Foursquare user's 800+ tips with their Saved and Like counts in an html table for reporting and analytics purposes. Here is an example of what I mean on foursquare: http://foursquare.com/redbull/list/tips . (Again, redbull is just my example..I am working with an organization that has 812 tips).
Foursquare provides an api to get to this data:
https://api.foursquare.com/v2/lists/{USER-ID}/tips?oauth_token={oauth-token}&limit=200&v=20120917
BUT you can only get 200 results at a time and must use an offset to get the next 200, 400 and so on:
https://api.foursquare.com/v2/lists/{USER-ID}/tips?oauth_token={oauth-token}&limit=200&offset=200&v=20120917
In my case I would need to call the API 5 times to get all 812 tips. I came up with a very clunky and unscalable solution where I do call the API multiple times and just keep creating rows in my table. Here is my ugly but working solution: http://pastebin.com/WL6kdTPY
But obviously as tips continue to grow I would need to keep modifying my code to account for each iteration of 200 more. In the API data I can see a mention of total tips (812) so I feel like I should be able to use that to come up with a more lean solution.
Can anyone help? Thanks!
Upvotes: 1
Views: 2312
Reputation: 96
A second loop should do the trick :
<?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 you check if the number of returned item is lower than the limit for each request. that should mean that you reached the end
Upvotes: 1