For each person, there is a key named favourite whose value is another JSON object. In our example JSON, there are three JSON objects each corresponding to the details about a person. The value of a JSON can be another JSON object. For example, to print all the name and id numbers from our example JSON document:Īccessing Nested objects inside a JSON array To access the objects inside a JSON array, the simplest and easiest method is to use a foreach loop to iterate through the array elements and fetch the data that you need. #Php json decode shows the type of object how toNote that the second argument in the json_decode function is set to true so that the objects returned will be associative arrays.įor more details on parsing JSON in PHP, read How to parse JSON in PHP Accessing objects inside a JSON array $json_string = file_get_contents($filepath) Firstly read the contents of the text file into a string variable using the file_get_contents() function and then use json_decode() function to convert the JSON string to a PHP variable. "favourite": Ĭonsider that our example JSON is stored in a file named "persons.txt". Let's look at some examples for accessing data a nested JSON document like below. One method is to use recursion just like you access data from a nested array or tree data structure. JSON objects are key-value pairs and there are different methods you can use to access JSON objects from a nested JSON document. A JSON document can have JSON objects nested inside other JSON objects.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |