PHP - Access JSON data structure

By xngo on September 12, 2019

In PHP, you can convert JSON string to an array or to an object using json_decode() function. In the examples below, I will show how to traverse JSON data as an array and as an object.

Convert JSON to object

$json_str = '[{
                "persons": [
                        { "name": "Joe", "age": 12 },
                        { "name": "Tom", "age": 14}
                    ]
            }]';
 
// Convert JSON to object.
$json_obj = json_decode($json_str);
print_r($json_obj);
 
echo "\n------------- Access to Tom's data. -------------\n";
print_r($json_obj[0]->persons[1]);

Output

Array
(
    [0] => stdClass Object
        (
            [persons] => Array
                (
                    [0] => stdClass Object
                        (
                            [name] => Joe
                            [age] => 12
                        )
 
                    [1] => stdClass Object
                        (
                            [name] => Tom
                            [age] => 14
                        )
 
                )
 
        )
 
)
 
------------- Access to Tom's data. -------------
stdClass Object
(
    [name] => Tom
    [age] => 14
)

Convert JSON to array

$json_str = '[{
                "persons": [
                        { "name": "Joe", "age": 12 },
                        { "name": "Tom", "age": 14}
                    ]
            }]';
 
// Convert JSON to array.
$json_array = json_decode($json_str, true);
print_r($json_array);
 
echo "\n------------- Access to Tom's data. -------------\n";
print_r($json_array[0]['persons'][1]);

Output

Array
(
    [0] => Array
        (
            [persons] => Array
                (
                    [0] => Array
                        (
                            [name] => Joe
                            [age] => 12
                        )
 
                    [1] => Array
                        (
                            [name] => Tom
                            [age] => 14
                        )
 
                )
 
        )
 
)
 
------------- Access to Tom's data. -------------
Array
(
    [name] => Tom
    [age] => 14
)

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.