简体   繁体   English

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

[英]How can I use PHP to get the nth item in a JSON object?

Ok, so the twitter daily trends list is 20 trends long. 好的,所以推特每日趋势列表是20个趋势长。 Let's say I want to get the 7th trend on the list. 假设我想在列表中获得第7个趋势。 Here's my longwinded way of doing it... 这是我漫无边际的做法......

// 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;

I suspect I'm confusing objects and arrays, but I'm sure there is a much simpler way of doing this than with those two for/each loops because 我怀疑我混淆了对象和数组,但我确信有一个更简单的方法来做这个,而不是那两个for / each循环,因为

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

Gives me this error: 给我这个错误:

Fatal error: Cannot use object of type stdClass as array 

Thanks for your help! 谢谢你的帮助!

$json_output = json_decode($json);

must be: 一定是:

$json_output = json_decode($json,true);

(You have to tell json to convert the stdClass to arrays) (你必须告诉json将stdClass转换为数组)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM