I've started working with the Twitter API and Abraham's TwitterOAuth
wrapper to retrieve Twitter data, but I can't figure out how to access objects within the array returned. The data is structured like so:
array(1) { [0]=> object(stdClass)#462 (24) {
["created_at"]=> string(30) "Tue Sep 11 03:30:54 +0000 2018"
["id"]=> int(120823024720)
["id_str"]=> string(19) "1268383623782373"
["text"]=> string(141) "RT @user: tweet tweet tweet tweet tweet"
["truncated"]=> bool(false)
["entities"]=> object(stdClass)#463 (4) {
["hashtags"]=> array(0) { }
["symbols"]=> array(0) { }
["user_mentions"]=> array(1) {
[0]=> object(stdClass)#464 (5) {
["screen_name"]=> string(6) "user"
["name"]=> string(3) "username"
["id"]=> int(12361328)
["id_str"]=> string(8) "12342312"
["indices"]=> array(2) {
[0]=> int(3)
[1]=> int(10) } } }
["urls"]=> array(0) { } }
["source"]=> string(82) "Twitter for iPhone"
["in_reply_to_status_id"]=> NULL
["in_reply_to_status_id_str"]=> NULL
["in_reply_to_user_id"]=> NULL
["in_reply_to_user_id_str"]=> NULL
["in_reply_to_screen_name"]=> NULL
["user"]=> object(stdClass)#465 (42)
There are many more layers, as tweets are actually extremely complex. I can access the first few pieces of data before the entities
object, but, how do I access these sub-layers? Say, for instance, I want to access the screen name of the user. I have tried like so:
$data->entities->user_mentions->screen_name;
But I really have no idea to sort through this nested data. How do I navigate this data structure and access the different pieces of it?
First, the response is an array. So to get the first item from the array,
//get first item
$tweet = $data[0];
//user_mentions is also an array
$mention = $tweet->entities->user_mentions[0];
//now you can access the screen name with
$mention->screen_name;
If you wanted to iterate through an array of tweets,
foreach( $data as $tweet ) {
$mention = $tweet->entities->user_mentions[0];
echo $mention->screen_name;
}
Overall a fairly broad question. You should look into working with Arrays and Objects in PHP.