Home >Backend Development >PHP Tutorial >How to Decode JSON into an Array Instead of an Object in PHP?
JSON Decoding: Creating an Array Rather Than an Object
Decoding JSON strings into associative arrays instead of objects is essential for many programming tasks. When encountering errors like "Fatal error: Cannot use object of type stdClass as array," it indicates that the decoded JSON was misinterpreted as an object rather than an array.
In PHP, the json_decode() function allows you to specify the desired format of the decoded output. To obtain an array instead of an object, you need to provide the second argument as true:
$result = json_decode($jsondata, true);
This modification will decode the JSON string into an associative array, allowing you to access its values using array syntax:
print_r($result['Result']);
Alternatively, if you prefer integer keys for the array elements:
$result = array_values(json_decode($jsondata, true));
However, if you prefer to use the JSON string as an object, you can access its properties using the arrow operator:
print_r($obj->Result);
The above is the detailed content of How to Decode JSON into an Array Instead of an Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!