Home > Backend Development > PHP Tutorial > How to Correctly Decode JSON into an Array in PHP?

How to Correctly Decode JSON into an Array in PHP?

Mary-Kate Olsen
Release: 2024-12-27 18:35:14
Original
190 people have browsed it

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

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

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

However, if you prefer the object-based approach, access the properties directly via dot notation.

print_r($obj->Result);
Copy after login

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!

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