json_decode() 期望参数 1 为字符串,数组给定

json_decode() expects parameter 1 to be string, array given

我有以下代码,我在 HTML 页面上以 JSON 格式获取推文,我希望它在 HTML 页面上整齐地显示。我已经包含了 foreach 循环,但是我收到以下错误:“json_decode() expects parameter 1 to be string, array given”。

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) 
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

$resArr = json_decode($tweets, 1); // decodes the json string to an array

if (is_array($resArr))
{
    foreach ($resArr as $tweet)
    {
        echo $tweet['text']."<br />";
    }
}

在阅读了其他建议后,我也尝试使用以下代码,但是出现错误"Using $this when not in object context":

$resArr = json_decode($this->item->extra_fields, true); 

谁能给我一些指导?

您的错误 "json_decode() expects parameter 1 to be string, array given" 暗示 $tweets 已经是一个数组(不是字符串)。请尝试以下操作:

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

foreach ($tweets as $tweet)
{
    echo $tweet->text."<br />";
}

因为我已经从使用数组切换到使用对象,所以我不得不按如下方式更改 PHP 代码。

foreach ($tweets as $tweet)
{
    echo $tweet->text;
    echo "<br />\n";
}

这个答案解释得最好,