PHP MySQL : 通过循环迭代将 Json 响应值插入数据库
PHP MySQL : inserting Json response values into database by iterating through loops
我有一个 JSON 响应,我想将其存储在数据库中。
但是在这里我无法遍历内部循环中的值。
JSON 推特数据:
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
遍历循环。但是如果没有发布主题标签,这 returns 我会出错。
代码:
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,另外两条是纯文本。当我 运行 我的代码时,对于第一次迭代它运行良好,但是对于第 2 次和第 3 次迭代它 returns 我一个错误 PHP Notice:Undefined offset: 1
, PHP Notice:Undefined offset: 2
.
这是因为我的另外两条推文不包含主题标签,但我的代码仍在尝试访问它。这里我想在该字段没有值时将 NULL 值存储到数据库中。我怎样才能做到这一点?
感谢您的帮助。
只有一个主题标签,因此它会在 0
上,第 2 和第 3 个循环 $i
将是 1
,2
不存在。将 $i
替换为 0
并为其添加检查,否则将空白存储到 $hashtag_text
。试试 -
$hashtag_text = !empty($json[$i]->entities->hashtags[0]->text) ? $json[$i]->entities->hashtags[0]->text : '';
我有一个 JSON 响应,我想将其存储在数据库中。 但是在这里我无法遍历内部循环中的值。
JSON 推特数据:
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
遍历循环。但是如果没有发布主题标签,这 returns 我会出错。
代码:
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,另外两条是纯文本。当我 运行 我的代码时,对于第一次迭代它运行良好,但是对于第 2 次和第 3 次迭代它 returns 我一个错误 PHP Notice:Undefined offset: 1
, PHP Notice:Undefined offset: 2
.
这是因为我的另外两条推文不包含主题标签,但我的代码仍在尝试访问它。这里我想在该字段没有值时将 NULL 值存储到数据库中。我怎样才能做到这一点?
感谢您的帮助。
只有一个主题标签,因此它会在 0
上,第 2 和第 3 个循环 $i
将是 1
,2
不存在。将 $i
替换为 0
并为其添加检查,否则将空白存储到 $hashtag_text
。试试 -
$hashtag_text = !empty($json[$i]->entities->hashtags[0]->text) ? $json[$i]->entities->hashtags[0]->text : '';