【问题标题】:PHP MySQL : inserting Json response values into database by iterating through loopsPHP MySQL:通过循环迭代将 Json 响应值插入数据库
【发布时间】: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: 1PHP Notice:Undefined offset: 2

这是因为我的其他两条推文不包含主题标签,而我的代码仍在尝试访问它。在这里,当该字段没有值时,我想将 NULL 值存储到数据库中。我怎样才能做到这一点?

感谢您的帮助。

【问题讨论】:

  • 使用foreach 而不是while

标签: php mysql json twitter


【解决方案1】:

只有一个标签,所以它会出现在0,第二和第三循环$i 将是12 不存在。将$i 替换为0 并为它添加一个检查,否则将空白存储到$hashtag_text。试试 -

$hashtag_text = !empty($json[$i]->entities->hashtags[0]->text) ? $json[$i]->entities->hashtags[0]->text : '';

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2012-04-23
    相关资源
    最近更新 更多