In web development, it often involves submitting data in JSON format from the front-end page to the back-end, and then converting the data into an array or object form that PHP can operate. This article will introduce how to use PHP to convert JSON data into array objects.
JSON is a lightweight data exchange format with clear structure and easy to read and write. PHP has built-in JSON processing functions, which can easily convert JSON into array or object form.
Suppose we have the following JSON data:
{ "name": "Tom", "age": 20, "address": { "province": "Guangdong", "city": "Guangzhou" }, "hobbies": [ "reading", "swimming" ] }
Use PHP's json_decode()
function to convert it into an array object. The usage of the function is as follows:
array|object json_decode(string $json[, bool $assoc = false[, int $depth = 512[, int $options = 0]]])
Parameter description:
Code example:
$jsonStr = '{ "name": "Tom", "age": 20, "address": { "province": "Guangdong", "city": "Guangzhou" }, "hobbies": [ "reading", "swimming" ] }'; $array = json_decode($jsonStr, true); print_r($array);
Output result:
Array ( [name] => Tom [age] => 20 [address] => Array ( [province] => Guangdong [city] => Guangzhou ) [hobbies] => Array ( [0] => reading [1] => swimming ) )
As you can see, the json_decode()
function converts the JSON string into PHP Array object.
If you want to convert JSON data into PHP object form, you can remove the second parameter in the function or set it to false.
In addition to converting JSON data into array or object form, PHP can also encode data in array or object form into JSON string. This can be achieved using PHP's json_encode()
function. Function usage is as follows:
string json_encode(mixed $value[, int $options = 0[, int $depth = 512]])
Parameter description:
Code example:
$array = array( 'name' => 'Tom', 'age' => 20, 'address' => array( 'province' => 'Guangdong', 'city' => 'Guangzhou' ), 'hobbies' => array( 'reading', 'swimming' ) ); $jsonStr = json_encode($array, JSON_PRETTY_PRINT); echo $jsonStr;
Output result:
{ "name": "Tom", "age": 20, "address": { "province": "Guangdong", "city": "Guangzhou" }, "hobbies": [ "reading", "swimming" ] }
In actual development, AJAX technology is often used to submit JSON data to the back-end server, and then through PHP Convert it into actionable form. Mastering the above JSON-related PHP functions will make it easier to process JSON data.
The above is the detailed content of php convert json to array object. For more information, please follow other related articles on the PHP Chinese website!