【发布时间】:2015-07-08 05:56:44
【问题描述】:
我有一个想要存储在数据库中的 JSON 响应。 但是在这里我无法遍历内部循环中的值。
JSON Twitter 数据:
Array
(
[0] => stdClass Object
(
[created_at] => Thu Apr 23 05:23:39 +0000 2015
[id_str] => 591110161239945216
[entities] => stdClass Object
(
[hashtags] => Array
(
[0] => stdClass Object
(
[text] => HelloWorld
[indices] => Array
(
[0] => 0
[1] => 11
)
)
)
)
)
)
我在这里尝试访问[text]=>helloworld 字段并将其插入数据库。我想使用while 遍历循环。但是,如果没有发布主题标签,这会给我一个错误。
代码:
i=0
while($i<3)
{
$tweet_id = $json[$i]->id_str;
$created_at = $json[$i]->created_at;
$hashtag_text = $json[$i]->entities->hashtags[$i]->text;
$this->sql="INSERT INTO twitter_scan('tweetid','created_at','hashtag_text'). VALUES('$tweet_id','$created_at','$hashtag_text')";
$this->query=mysqli_query($this->conn,$this->sql);
$i++;
}
我的帐户中有 3 条推文,其中 1 条推文带有#hashtag,另外两条是纯文本。当我运行我的代码时,对于第一次迭代它运行良好,但对于第二次和第三次迭代它返回一个错误 PHP Notice:Undefined offset: 1 , PHP Notice:Undefined offset: 2。
这是因为我的其他两条推文不包含主题标签,而我的代码仍在尝试访问它。在这里,当该字段没有值时,我想将 NULL 值存储到数据库中。我怎样才能做到这一点?
感谢您的帮助。
【问题讨论】:
-
使用
foreach而不是while。