Home >Backend Development >PHP Tutorial >How to Correctly Decode JSON into an Array in PHP?
Creating an Array from JSON Using json_decode()
In decoding a JSON string, it's intended to obtain an array instead of an object. However, encountering the error message "Fatal error: Cannot use object of type stdClass as array" indicates an incorrect approach.
The code provided:
$json_string = 'http://www.example.com/jsondata.json'; $jsondata = file_get_contents($json_string); $obj = json_decode($jsondata); print_r($obj['Result']);
performs object-based decoding by default. To rectify this issue and generate an array, the second parameter in json_decode() should be set to true.
$result = json_decode($jsondata, true);
This action returns an associative array.
Alternatively, you can convert the associative array to a numerically indexed array using array_values().
$result = array_values(json_decode($jsondata, true));
However, if you prefer the object-based approach, access the properties directly via dot notation.
print_r($obj->Result);
The above is the detailed content of How to Correctly Decode JSON into an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!