开发者

Check if an item isset in a decoded JSON string

I'm working on a module which loads data from Twitter's user_timeline REST API. Once I have the JSON decoded,开发者_JAVA百科 I do a foreach statement in my PHP to get each of the returned tweets. I'm currently having an issue checking for items under the retweeted_status portion of the JSON string. The JSON I'm calling is:

"http://api.twitter.com/1/statuses/user_timeline.json?count=".$count."&include_rts=1&screen_name=".$uname.""

retweeted_status is only returned if a tweet is a retweet. So, for example, if the tweet is a retweet, I want to return the original tweet's text, not the retweet. I've tried this code:

if(isset($t->retweeted_status->text)) {
    $tweet = $t->retweeted_status->text;
} else {
    $tweet = $t->text;
}

Using the above code, when retweeted_status is NOT returned, isset is still true for all objects after the first time the isset is returned true.

What I need is a conditional within my foreach that will properly check for items under retweeted_status (since the retweeted datapoint is disabled and has been for some time) and reset the check to false if retweeted_status is not present.

Any suggestions?


PHP has excellent JSON support built-in, so there's no need to manually grokk through the JSON string to find out whether or not the object it represents has a given property. Just do

$twitterObj = json_decode( $responseTextFromTwitterAPI [, true ] );

with the second param = true if the JSON string represents an associative array, false if it's a "plain" (integer-indexed) one. (You'll want to check Twitter's docs to find out.) Then your checks should amount to something like (I'm not familiar with Twitter's API spec...):

foreach ( $twitterObj as $tweet ) {
    if ( isset( $tweet['retweeted_status'] ) ) {
        // Retweet
    } else {
        // Original
    }
    // Do stuff...
}

EDIT:

This works for me:

$obj = json_decode( $jsonFromTwitter, true );
foreach ( $obj as $o ) {
if ( isset($o['retweeted_status']) ) {
   echo $o['retweeted_status']['text'];
} else {
    echo $o['text];
}

You should be able to get where you want from there, right?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜