Home  >  Article  >  Backend Development  >  Convert array to json in php

Convert array to json in php

PHPz
PHPzOriginal
2023-05-06 19:52:06568browse

In PHP, converting an array to JSON format is very simple. Currently, JSON, as a data transmission and storage format, has been widely used in Web services. For example, data exchange between the client and the server will use JSON format for data transmission. In PHP, you can use built-in functions to convert an array into JSON format.

PHP provides the json_encode() function, which converts a PHP array into JSON format. The following is a simple example:

// 声明一个PHP数组
$person = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York"
);

// 将PHP数组转换成JSON
$json = json_encode($person);

// 输出JSON字符串
echo $json;

Run the above code, you will get a JSON string similar to the following:

{"name":"John","age":30,"city":"New York"}

If you want to convert a multi-dimensional array into JSON format, it is also very easy. Simple. As long as the hierarchy and structure of the PHP array are correct, the json_encode() function will convert it into JSON format.

The following is an example of a multi-dimensional array:

// 声明一个PHP多维数组
$person = array(
    "name" => "John",
    "age" => 30,
    "city" => "New York",
    "contact" => array(
        "email" => "john@example.com",
        "phone" => "1234567890"
    ),
    "friends" => array(
        array(
            "name" => "Mary",
            "age" => 25
        ),
        array(
            "name" => "Peter",
            "age" => 27
        )
    )
);

// 将PHP数组转换成JSON
$json = json_encode($person);

// 输出JSON字符串
echo $json;

The above code will get the following JSON string:

{
    "name": "John",
    "age": 30,
    "city": "New York",
    "contact": {
        "email": "john@example.com",
        "phone": "1234567890"
    },
    "friends": [
        {
            "name": "Mary",
            "age": 25
        },
        {
            "name": "Peter",
            "age": 27
        }
    ]
}

The above is to convert the PHP array into JSON format Simple example of . We can see that the json_encode() function is very convenient and can convert a PHP array and the sub-information contained into a JSON format string with a simple call.

The above is the detailed content of Convert array to json 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