In the process of web development, it is often necessary to convert PHP and JSON data to each other. For PHP developers, PHP provides some convenient functions to convert between JSON data and PHP arrays.
This article will introduce how to convert JSON data to PHP array and convert PHP array to JSON data in PHP.
1. Convert JSON data to PHP array
JSON (JavaScript Object Notation) is a lightweight data exchange format that is often used in data transfer situations. PHP converts JSON data into PHP arrays through the json_decode() function.
The json_decode() function accepts two parameters: the JSON string to be decoded and an optional Boolean parameter indicating whether to convert the JSON object to an associative array. By default, the json_decode() function converts JSON objects into PHP objects.
The following is an example of converting JSON data to PHP array:
<?php $json_string = '{"name":"John", "age":30, "city":"New York"}'; $php_array = json_decode($json_string, true); print_r($php_array); ?>
Output result:
Array ( [name] => John [age] => 30 [city] => New York )
2. Convert PHP array to JSON data
PHP Array is a simple and useful data structure often used in web development. Sometimes it is necessary to convert PHP arrays to JSON data to facilitate data exchange between different platforms. PHP uses the json_encode() function to convert PHP arrays to JSON data.
The json_encode() function accepts one parameter: the PHP array or object to be encoded. This function returns a string representing the encoded JSON data.
The following is an example of converting a PHP array to JSON data:
<?php $php_array = array( "name" => "John", "age" => 30, "city" => "New York" ); $json_string = json_encode($php_array); echo $json_string; ?>
Output results:
{"name":"John","age":30,"city":"New York"}
Summary
This article introduces how to convert a PHP array to JSON data in PHP Convert JSON data to PHP arrays, and convert PHP arrays to JSON data. PHP provides json_decode() and json_encode() functions to accomplish this task. In actual development, this kind of data conversion is very common and necessary and requires skillful application.
The above is the detailed content of How to convert php+json data into an array. For more information, please follow other related articles on the PHP Chinese website!