Home >Backend Development >PHP Tutorial >Detailed explanation of json_encode() and json_decode() functions in php
Before introducing these two functions, I still want to talk about json. I don’t know how much you know about json. I feel that after I have been exposed to php for a while, I have some impressions of json, but it is just an impression. I only know that it is a data type and is relatively lightweight. But I'm really vague about its structure, and I didn't understand it until I used it now, so: Practice is a very effective way to test whether you have gained true knowledge.
1: The first is json_encode(), which means converting data to json format. So what type of data can be converted to json format?
1. Object.
Define a class, new an object, you can convert the object into json format
<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e); ?>
Result
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
2. Array.
Define an array of key-value pairs
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>
Result
{"a":1,"b":2,"c":3,"d":4,"e":5}
We can know that they are all converted to json format data. In fact, the point is not that the results are the same, because they are all converted to json? . What we need to know is that the data types that can be converted to json format are objects and arrays of key-value pairs
2: The second is json_decode(). Decode the JSON format string and convert it into a PHP variable.
First enter the code
Print the result
object(stdClass)#1 (5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) } array(5) { ["a"] => int(1) ["b"] => int(2) ["c"] => int(3) ["d"] => int(4) ["e"] => int(5) }
Here we can clearly see the first one The printed result is an object and the second is an array of key-value pairs.
In this way we can explain the second parameter of json_decode() well:
When it is true: it returns an array; when it is false (default is false): it returns an object.
Related recommendations:
Detailed explanation of json_encode() function in php
PHP Detailed explanation of json_encode() function and Chinese garbled code problem
PHP json_encode() function introduction
The above is the detailed content of Detailed explanation of json_encode() and json_decode() functions in php. For more information, please follow other related articles on the PHP Chinese website!