In PHP, we often need to convert JSON strings into array format to operate data, so how to implement this function? Next, this article will take you step by step to learn how to convert a JSON string into an array.
1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to read and easy to write. Its syntax is similar to XML, but JSON is more concise and clear, and is suitable for data transmission and storage.
JSON specifies two data structures, namely "key-value pair" and "array". Among them, "key-value pair" refers to a mapping between a set of keys and values, and "array" is an ordered list of values.
A simple JSON data example:
{ "name": "小明", "age": 18, "hobbies": ["听音乐", "读书", "旅游"] }
2. The json_decode function in PHP
In PHP, we can use the json_decode function to convert the JSON string into array format .
The usage is as follows:
$array = json_decode($jsonString, true);
Among them, $jsonString represents the JSON string to be converted, and true represents the conversion result to be converted into an associative array.
The following is a sample code:
$json = '{"name": "小明", "age": 18, "hobbies": ["听音乐", "读书", "旅游"]}'; $array = json_decode($json, true); print_r($array);
Output result:
Array ( [name] => 小明 [age] => 18 [hobbies] => Array ( [0] => 听音乐 [1] => 读书 [2] => 旅游 ) )
In the above code, we passed in a "key-value pair" and "array" JSON string, then use the json_decode function to convert it into an array, and print the result.
3. Notes on the json_decode function in PHP
4. Summary
This article introduces in detail the method of converting JSON strings into arrays in PHP, and introduces the precautions of the json_decode function. After studying this article, I believe that readers can master the basic method of converting JSON strings into arrays. I hope it will be helpful to you.
The above is the detailed content of How to convert json string to array in php. For more information, please follow other related articles on the PHP Chinese website!