Home  >  Article  >  Backend Development  >  php json to array

php json to array

王林
王林Original
2023-05-22 21:56:08618browse

In PHP development, we often use data in JSON format. When processing this data, we need to convert JSON into a PHP array for operation. Two commonly used methods are introduced below: using the json_decode() function and using the json_decode() function combined with the second parameter true.

Method 1: Use the json_decode() function

The json_decode() function is PHP’s built-in JSON decoding function, which can convert a JSON string into a PHP array. Before using this function to convert, you need to convert the JSON string to UTF-8 format first, because the json_decode() function only supports data in UTF-8 format.

The following is a simple example:

$json_str = '{"name":"张三","age":18,"gender":"男"}'; // 示例JSON字符串
$arr = json_decode($json_str, true); // 将JSON字符串转换成PHP数组
print_r($arr); // 打印数组

The running results are as follows:

Array
(
    [name] => 张三
    [age] => 18
    [gender] => 男
)

Method 2: Use the json_decode() function combined with the second parameter true

The second parameter true represents converting JSON data into an Associative Array. The principle is similar to method 1, except that when using the json_decode() function, you need to add the second parameter true.

The following is a simple example:

$json_str = '{"name":"张三","age":18,"gender":"男"}'; // 示例JSON字符串
$arr = json_decode($json_str, true); // 将JSON字符串转换成PHP关联数组
print_r($arr); // 打印数组

The running result is the same as method one:

Array
(
    [name] => 张三
    [age] => 18
    [gender] => 男
)

It should be noted here that the json_decode() function converts JSON data by default into an object type. If you want to convert it into an array type, you need to pass true in the second parameter position.

Summary

Using the above two methods can easily convert JSON data into PHP arrays, which facilitates us to perform various operations during development. It should be noted that when using the json_decode() function, you need to ensure that the format of the JSON string is correct, otherwise null will be returned. When using the json_decode() function, you also need to pay attention to transcoding issues, otherwise garbled characters will appear. In addition, since PHP arrays and JSON data are very similar in structure, PHP arrays can also be converted into JSON format data. For specific methods, please refer to the official PHP documentation.

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