How to convert JSON data into array object in php

PHPz
Release: 2023-04-23 09:18:37
Original
369 people have browsed it

During the development process, we often involve scenarios of converting JSON data into arrays or object arrays. As a popular server-side programming language, PHP also provides convenient methods to perform conversion operations when processing JSON data. This article uses an example to demonstrate how to convert JSON data into an array of array objects.

Prerequisite knowledge

Before explaining the specific operations, you need to understand some basic PHP knowledge.

JSON

JSON (short for JavaScript Object Notation) is a lightweight data exchange format. It represents data as key-value pairs or array format. JSON data can be represented using objects and arrays in JavaScript.

Array in PHP

In PHP, an array is a structure that collects data. It can store different types of values. In an array, each value has a key associated with it, and the key can be any string or integer.

stdClass object in PHP

stdClass object is a very simple object model in PHP. It can dynamically allocate properties as needed. In addition, it can also convert objects into arrays or Arrays are converted to objects, which is useful for working with JSON data.

Convert Json to Array

Let’s first take a look at how to convert JSON data into a PHP array. PHP provides a built-in function json_decode(), which can convert a JSON string into a PHP array. The usage of this function is as follows:

mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
Copy after login

Among them, $json represents the JSON string that needs to be converted; $assoc represents whether to return an associative array (the default is false, which means returning an object); $depth represents the maximum recursion depth (default is 512); $options represents conversion options (default is 0).

Here is a simple example, assuming we have a file containing JSON datadata.json:

{
    "name": "Typechoer",
    "age": 25,
    "gender": "male",
    "skills": ["PHP", "JavaScript", "CSS"]
}
Copy after login

We can use the following code to read the JSON data and It is converted into a PHP array:

$json = file_get_contents('data.json');
$data = json_decode($json, true);
print_r($data);
Copy after login
Copy after login

The output result is as follows:

Array
(
    [name] => Typechoer
    [age] => 25
    [gender] => male
    [skills] => Array
        (
            [0] => PHP
            [1] => JavaScript
            [2] => CSS
        )
)
Copy after login
Copy after login

As you can see, we have implemented the operation of converting JSON data into a PHP array, and the type of data remains unchanged.

Convert Json to object array

In addition to converting JSON data into a PHP array, you can also convert it into an object array. An object array is an array of stdClass objects, where each object represents an element. We don't need to care about the field names of the object, we only need to access them through the properties of the object. The following is a method to convert JSON data into an array of PHP objects:

json_decode(string, false, 512, JSON_OBJECT_AS_ARRAY);
Copy after login

As you can see, we only need to set the $assoc parameter to false, set the $options parameter to JSON_OBJECT_AS_ARRAY, and then use the json_decode() function Just perform the conversion operation.

Similarly based on the above JSON data, we can use the following code to convert it into a PHP object array:

$json = file_get_contents('data.json');
$data = json_decode($json, false, 512, JSON_OBJECT_AS_ARRAY);
print_r($data);
Copy after login
Copy after login

The output result is as follows:

Array
(
    [name] => Typechoer
    [age] => 25
    [gender] => male
    [skills] => Array
        (
            [0] => PHP
            [1] => JavaScript
            [2] => CSS
        )
)
Copy after login
Copy after login

Since an object array is used , so we can use object properties to access data, for example:

echo $data[0]->name; // Typechoer
echo $data[0]->skills[2]; // CSS
Copy after login

Json converted into a multi-dimensional array

If the JSON data has sub-objects or arrays nested in it, then converted into a PHP array or object When using an array, we can still maintain the multi-dimensional nature of the data.

The following is an example of JSON data with a nested structure:

{
    "account": {
        "name": "Tom",
        "age": 28
    },
    "courses": [
        {
            "name": "PHP",
            "hour": 80
        },
        {
            "name": "JavaScript",
            "hour": 60
        }
    ]
}
Copy after login

We can use the following code to convert it into a PHP array:

$json = file_get_contents('data.json');
$data = json_decode($json, true);
print_r($data);
Copy after login
Copy after login

The output result is as follows:

Array
(
    [account] => Array
        (
            [name] => Tom
            [age] => 28
        )

    [courses] => Array
        (
            [0] => Array
                (
                    [name] => PHP
                    [hour] => 80
                )

            [1] => Array
                (
                    [name] => JavaScript
                    [hour] => 60
                )

        )

)
Copy after login
Copy after login

Similarly, we can also convert it into a PHP object array:

$json = file_get_contents('data.json');
$data = json_decode($json, false, 512, JSON_OBJECT_AS_ARRAY);
print_r($data);
Copy after login
Copy after login

The output result is as follows:

Array
(
    [account] => Array
        (
            [name] => Tom
            [age] => 28
        )

    [courses] => Array
        (
            [0] => Array
                (
                    [name] => PHP
                    [hour] => 80
                )

            [1] => Array
                (
                    [name] => JavaScript
                    [hour] => 60
                )

        )

)
Copy after login
Copy after login

As you can see, the structure of multi-dimensional data is preserved.

Summary

In this article, we introduced how to convert JSON data into a PHP array or object array. Using PHP's built-in function json_decode(), we can quickly convert between JSON data and PHP data. If you need to deal with JSON data in development, then this knowledge will definitely help you.

The above is the detailed content of How to convert JSON data into array 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!