【问题标题】:json_decode() expects parameter 1 to be string, array givenjson_decode() 期望参数 1 是字符串,给定数组
【发布时间】:2015-07-12 21:27:36
【问题描述】:

我有以下代码,其中我在 HTML 页面上获取 JSON 格式的推文,我希望它能够整齐地显示在 HTML 页面上。我已经包含了 foreach 循环,但是我收到以下错误:“ json_decode() 期望参数 1 是字符串,给定数组”。

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

在阅读其他建议后,我也尝试使用以下代码,但是出现错误“在不在对象上下文中使用 $this”:

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

有人能给我一些指导吗?

【问题讨论】:

    标签: arrays json twitter decode


    【解决方案1】:

    您的错误“json_decode() 期望参数 1 是字符串,给定数组”暗示 $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 />";
    }
    

    【讨论】:

    • 我试过了,但是我得到了以下错误:“不能使用 stdClass 类型的对象作为数组”
    • 已编辑:使用 -> 代替 []
    【解决方案2】:

    由于我已从使用数组切换到使用对象,因此我必须按如下方式更改 PHP 代码。

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

    这个答案解释得最好,https://stackoverflow.com/a/16589380/2675041

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-11
      • 2021-01-13
      • 2016-04-30
      • 2014-12-09
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多