如何使用PHP获取JSON对象中的第n个项?

时间:2010-06-24 14:34:06

标签: php json twitter

好的,所以twitter每日趋势列表有20个趋势。假设我想在列表中获得第7个趋势。这是我漫无边际的做法......

// We want the 7th item in the array
$trendArray = 7;

// Get an array (?) of the latest twitter trends
$jsonurl = "http://search.twitter.com/trends/daily.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
$allTrends = $json_output->trends;

// Cycle through to the 7th in the list
foreach ( $json_output->trends as $trendslist ) {
    foreach ( $trendslist as $trend ) {
            $loop += 1;
            if ($loop == $trendArray) {     
                $theTrend = $trend->name;
                break;  
            }
    }
    break; // Exit after we've looped once
}   

echo $theTrend;

我怀疑我混淆了对象和数组,但我确信有一种更简单的方法可以做到这一点,而不是那两个for / each循环,因为

$theTrend = $json_output->trends[6]->name;

给我这个错误:

Fatal error: Cannot use object of type stdClass as array 

感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

$json_output = json_decode($json);

必须是:

$json_output = json_decode($json,true);

(你必须告诉json将stdClass转换为数组)

编辑:见http://php.net/manual/en/function.json-decode.php