PHP Serialization functions are often used. when you need to store data in a database or file, you can use serialize () and unserialize () in PHP () method to implement serialization and deserialization. the code is as follows:
PHP Serialization functions are often used. when you need to store data in a database or file, you can use serialize () and unserialize () in PHP () method to achieve serialization and deserialization, the code is as follows:
Php code
- // A complex array
- $ Myvar = array (
- 'Hello ',
- 42,
- Array (1, 'two '),
- 'Apple'
- );
- // Serialization
- $ String = serialize ($ myvar );
- Echo $ string;
- /* Output
- A: 4: {I: 0; s: 5: "hello"; I: 1; I: 42; I: 2; a: 2: {I: 0; I: 1; I: 1; s: 3: "two";} I: 3; s: 5: "apple ";}
- */
- // Reverse sample
- $ Newvar = unserialize ($ string );
- Print_r ($ newvar );
- /* Output
- Array
- (
- [0] => hello
- [1] => 42
- [2] => Array
- (
- [0] => 1
- [1] => two
- )
- [3] => apple
- )
- */
How to serialize data to json format? rest assured that php is ready for you. users who use php 5.2 or later can use the json_encode () and json_decode () functions to serialize data in json format, the code is as follows:
Php code
// A complex array
$ Myvar = array (
'Hello ',
42,
Array (1, 'two '),
'Apple'
);
// Convert to a string
$ String = json_encode ($ myvar );
Echo $ string;
/* Prints
["Hello", 42, [1, "two"], "apple"]
*/
// You can reproduce the original variable
$ Newvar = json_decode ($ string );
Print_r ($ newvar );
/* Prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/