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.
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 : '';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.