[英]PHP MySQL : inserting Json response values into database by iterating through loops
我有一个要存储在数据库中的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条Tweet,其中1条Tweet具有#hashtag,另2条是纯文本。 当我运行代码时,对于第一次迭代,它运行良好,但是对于第二次和第三次迭代,它向我返回错误PHP Notice:Undefined offset: 1
, PHP Notice:Undefined offset: 2
。
这是因为我的其他两个tweet不包含井号,而我的代码仍在尝试访问它。 在这里,当此字段没有值时,我想将NULL值存储到数据库。 我该如何实现?
感谢您的任何帮助。
只有一个主题标签,因此将是0
,第二和第三环$i
将是1
, 2
中不存在。 将$i
替换$i
0
并添加检查,否则将空白存储到$hashtag_text
。 尝试-
$hashtag_text = !empty($json[$i]->entities->hashtags[0]->text) ? $json[$i]->entities->hashtags[0]->text : '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.