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
Mary-Kate OlsenOriginal
2024-12-27 18:35:14124browse

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!

Statement:
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