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

3

好的,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个回答

6

澄清一下:一旦您添加了第二个参数,您就可以使用$theTrend = $json_output->trends[6]->name; - Ryan Kinal
他可以手动将stdClass转换为数组(array)$json_output->trends[6],但这种方式更简单xD(对我的英语表示抱歉) - cusspvz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接