0

I have a JSON response which I want to store in database. But here I am unable to loop through the values within the inner loops.

JSON Twitter Data:

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
          )
        )
      )
     )
   )       
 )

Here i am trying to access [text]=>helloworld field and insert it to database. I want to iterate through loop using while. But this returns me an error if there is no hashtags posted.

Code :

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++;
}

i have 3 tweets in my account out of which 1 tweet has a #hashtag other two are plain text. When I run my code, for the 1st iteration it works well, but for the 2nd and 3rd iteration it returns me an error PHP Notice:Undefined offset: 1 , PHP Notice:Undefined offset: 2.

This is because my other two tweets contain no hashtags and still my code is trying to access it. Here I want to store NULL value to database when there is no value for this field. How can I achieve this ?

Thank you for any help.

1
  • use foreach instead of while. Commented Apr 29, 2015 at 5:56

1 Answer 1

3

There is only one hashtag so it will be on 0, 2nd & 3rd loop $i will be 1, 2 which is not present. Replace $i with 0 & add a check for it else store blank to $hashtag_text. Try with -

$hashtag_text = !empty($json[$i]->entities->hashtags[0]->text) ? $json[$i]->entities->hashtags[0]->text : '';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.