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

Ric*_*erd 3 php twitter json

好的,所以推特每日趋势列表是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;
Run Code Online (Sandbox Code Playgroud)

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

$theTrend = $json_output->trends[6]->name;
Run Code Online (Sandbox Code Playgroud)

给我这个错误:

Fatal error: Cannot use object of type stdClass as array 
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

cus*_*pvz 6

$json_output = json_decode($json);
Run Code Online (Sandbox Code Playgroud)

一定是:

$json_output = json_decode($json,true);
Run Code Online (Sandbox Code Playgroud)

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

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