如何使用Twitter API 1.1获得前五大趋势?

时间:2017-01-26 17:00:13

标签: php twitter twitter-oauth

我正在使用Twitter API获取趋势。

我当前的代码显示了由WOEID,2295424标识的给定位置的所有趋势。如何更改它以仅显示前五大趋势?

<?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>";
    }
?>

1 个答案:

答案 0 :(得分:1)

这并不是Twitter特有的。所有你真正需要知道的是如何在X迭代后打破PHP循环。有各种方法可以做到这一点。一种简单的方法是跟踪计数器并使用break语句在达到所需值时退出循环。

<?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>";
    }
}
?>