Manikandan
Manikandan

Reputation: 512

How to get only top 5 trends with Twitter API 1.1?

I am getting trends using the Twitter API.

My current code displays all the trends for a given location identified by WOEID, 2295424 for example. How do I need to change it to display only the top five trends?

<?php
    $jsonop = $connection->get("trends/place", array('id' => '2295424'));
    //var_dump($statuses);
    foreach ($jsonop as $trend) {
        echo "As of {$trend->created_at} in ";
        foreach($trend->locations as $area)
            echo "{$area->name}";
        echo " the trends are:<br />";
        echo "<ul>";
        foreach($trend->trends as $tag)
            echo "<li>{$tag->name}</li>";
        echo "</ul>";
    }
?>

Upvotes: 1

Views: 265

Answers (1)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

This isn't really specific to Twitter. All you really need to know for this is how to break out of a PHP loop after X iterations. There are various ways to do that. A simple way is by keeping track of a counter and using a break statement to exit the loop when it reaches the desired value.

<?php
$jsonop = $connection->get("trends/place", array('id' => '2295424'));
//var_dump($statuses);
foreach ($jsonop as $trend) {
    echo "As of {$trend->created_at} in ";
    foreach($trend->locations as $area) {
        echo "{$area->name}";
        echo " the trends are:<br />";
        echo "<ul>";
        $counter = 0;
        foreach($trend->trends as $tag) {
            $counter++;
            echo "<li>{$tag->name}</li>";
            if ($counter == 5) break;
        }
        echo "</ul>";
    }
}
?>

Upvotes: 1

Related Questions