Home > Backend Development > PHP Problem > How to convert array into json data in php

How to convert array into json data in php

PHPz
Release: 2023-04-18 14:42:29
Original
448 people have browsed it

In PHP, it is very convenient to convert an array into json format. You only need to use the built-in json_encode function.

The json_encode function can convert any PHP data type into a json format string, including strings, numbers, Boolean values, arrays, objects, etc. Here is a simple example to demonstrate how to convert an array to json.

// 定义一个数组
$data = array(
  'name' => '小明',
  'age' => 25,
  'gender' => '男'
);

// 转换成json格式并打印出来
$json = json_encode($data);
echo $json;
Copy after login

Run the above code, the output result is as follows:

{"name":"小明","age":25,"gender":"男"}
Copy after login

You can see that this array is converted into a json format string. By default, the json_encode function will convert the key names in the array into attribute names in json format, and convert the key values ​​into attribute values ​​in json format.

In some specific occasions, we may need to control the output of json_encode. For example, we may need to specify indentation strings to make the output json format more readable. At this time, you can pass in an array of control options in the second parameter of the json_encode function.

For example, the following code specifies an indented string of 2 spaces:

// 定义一个数组
$data = array(
  'name' => '小明',
  'age' => 25,
  'gender' => '男'
);

// 指定缩进字符串并转换成json格式
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
Copy after login

Run the above code and the output will be as follows:

{
  "name": "小明",
  "age": 25,
  "gender": "男"
}
Copy after login

You can see that the output In the json format string, 2 spaces are indented between each attribute and the attribute value, making the entire string more readable.

In addition to specifying the indented string, the json_encode function also provides some other options, such as controlling the escaping of non-ASCII characters, controlling the date format, etc. For more details, please view the relevant documentation of the json_encode function in the PHP documentation.

The above is the detailed content of How to convert array into json data 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