简体   繁体   English

检查是否在解码的JSON字符串中设置了项目

[英]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. 我正在研究一个模块,该模块从Twitter的user_timeline REST API加载数据。 Once I have the JSON decoded, I do a foreach statement in my PHP to get each of the returned tweets. 解码完JSON之后,我就在PHP中执行了一条foreach语句来获取每个返回的tweet。 I'm currently having an issue checking for items under the retweeted_status portion of the JSON string. 我目前在检查JSON字符串的retweeted_status部分下的项目时遇到问题。 The JSON I'm calling is: 我正在调用的JSON是:

"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. 仅当推文为转发时,才返回retweeted_status。 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. 使用上面的代码,当未返回retweeted_status时,在第一次将isset返回true之后,isset对于所有对象仍然为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. 我需要的是在我的foreach中有条件的条件,可以有条件地检查retweeted_status下的项目(因为转推的数据点已禁用并且已经存在了一段时间),如果不存在retweeted_status,则将检查重置为false。

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. PHP具有内置的出色的JSON支持,因此无需手动遍历JSON字符串来查找它所表示的对象是否具有给定的属性。 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. 与第二PARAM = true ,如果JSON字符串代表一个关联数组,假如果它是一个“普通”(整数索引)之一。 (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...): (您将需要检查Twitter的文档以找出答案。)然后,您的检查应类似于(我不熟悉Twitter的API规范...):

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? 您应该能够从那里到达想要的地方,对吗?

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

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