json_decode()期望参数1为字符串,给定的是数组。
json_decode()期望参数1为字符串,给定的是数组。
我有以下代码,在HTML页面上以JSON格式获取推文,我希望能在HTML页面上整洁地显示。我已经包含了foreach循环,但是我遇到了以下错误:“json_decode()函数期望第一个参数是字符串,但是得到了一个数组”。
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); // 将json字符串解码为数组 if (is_array($resArr)) { foreach ($resArr as $tweet) { echo $tweet['text'].""; } }
我也尝试了使用以下代码,阅读其他建议后,但是出现了一个错误“在非对象上下文中使用$this”:
$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 />"; }
我尝试了这个方法,但是我得到了以下错误:"Cannot use object of type stdClass as array"
编辑:使用->代替[]。
问题的原因是,json_decode()函数期望传入一个字符串作为参数,但实际传入的是一个数组。解决方法是将数组转换为字符串,或者使用正确的参数类型。
在给定的代码中,错误信息提示$tweets是一个数组,因此应该将其转换为字符串。可以通过使用implode()函数将数组的元素连接起来,从而将其转换为字符串。修改后的代码如下:
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets); $tweetsString = implode("", $tweets); $json = json_decode($tweetsString); foreach ($json as $tweet) { echo $tweet->text.""; }
另一个错误"Cannot use object of type stdClass as array"表示尝试将stdClass对象作为数组使用。要解决此问题,可以使用对象的属性访问符"->"来访问对象的属性,而不是使用数组的语法"[]"。修改后的代码如下:
$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.""; }
通过以上修改,我们可以解决"json_decode() expects parameter 1 to be string, array given"和"Cannot use object of type stdClass as array"这两个错误。
从使用数组改为使用对象后,我不得不修改PHP代码,如下所示。
foreach ($tweets as $tweet) { echo $tweet->text; echo "<br />\n"; }
这个回答最好地解释了这个问题的原因和解决方法,https://stackoverflow.com/a/16589380/2675041