Access to JSON array after json_decode / multidimensional array

I am trying to do a search from Twitter Airlines, retrieving data using file_get_contents, and then passing in json_decode which give me this array structure.

{"results":[ { "from_user":"A-user-name", "from_user_id":457304735, "text":"Ich RU #BoysNoize #SuperRola", "entities":{ "urls":[{ "url":"http:\/\/t.co\/WZnUf68j", "expanded_url":"http:\/\/instagr.am\/p\/Vz4Nnbnjd6\/", }] }] ] 

This is repeated for each tweet. Now I can access the username and text using the foreach loop, and assign each instance of the results to a variable, and then pull the data from this variable.

 foreach($jsonArr['results'] as $item){ // Takes the Array jsonArr and for every results heading creates an $item $user = mysql_real_escape_string($item['from_user']); $text = mysql_real_escape_string($item['text']); 

This keeps the correct variables in order, but I cannot get the data in an array of objects in the results. If I print Entities var as username or text, I get

 ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray 

So, it contains arrays for each returned result, but how can I access it, I already messed around with several other methods that I know for accessing the array data, but they all seem flat. Any help on how to get these values ​​or integrate them with foreach would be greatly appreciated.

+4
source share
3 answers

Assuming you decide to decode JSON as a multidimensional array, not as objects:

 foreach ($results as $tweet) { $user = $tweet["from-user"]; $text = $tweet["text"]; $entities = $tweet["enities"]; $urls = $entities["urls"]; foreach ($urls as $url) { echo $url["expanded_url"]; } } 

et cetera

+4
source
 Array ( [results] => Array ( [0] => stdClass Object ( [entities] => Array ( [0] => stdClass Object ( [urls] => Array ( [0] => stdClass Object ( [expanded_url] => http://instagr.am/p/Vz4Nnbnjd6/ [url] => http://t.co/WZnUf68j ) ) ) ) [from_user] => A-user-name [from_user_id] => 457304735 [text] => Ich RU #BoysNoize #SuperRola ) ) ) 

URL access:

 $json_array['results'][0]->entities[0]->urls[0]->url; 

Useful code:

 <?php $json ='{ "results" : [ { "entities" : [ { "urls" : [ { "expanded_url" : "http://instagr.am/p/Vz4Nnbnjd6/", "url" : "http://t.co/WZnUf68j" } ] } ], "from_user" : "A-user-name", "from_user_id" : 457304735, "text" : "Ich RU #BoysNoize #SuperRola" } ] }'; $json_array = (array)(json_decode($json)); echo '<pre>'; //print_r($json_array); echo $json_array['results'][0]->entities[0]->urls[0]->url; 

? >

+4
source

Just do print_r($jsonArr); and you can work with your decoded json.

+2
source

All Articles