Home > Backend Development > PHP Tutorial > How to Decode JSON into an Array Instead of an Object in PHP?

How to Decode JSON into an Array Instead of an Object in PHP?

Barbara Streisand
Release: 2024-12-22 07:41:18
Original
791 people have browsed it

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);
Copy after login

This modification will decode the JSON string into an associative array, allowing you to access its values using array syntax:

print_r($result['Result']);
Copy after login

Alternatively, if you prefer integer keys for the array elements:

$result = array_values(json_decode($jsondata, true));
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template