This article mainly introduces PHP serialization function serialize () and unserialize () and PHP native serialization method comparison, the need for small partners can refer to.
In PHP, there is a good way to format a string and transform an array or object, that is, serialization processing.
There are two ways to serialize variables.
The following example uses the Serialize () and Unserialize () functions:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
A complex array $myvar = array (' Hello ', +, array (1, ' two '), ' Apple '); Convert to a string $string = Serialize ($myvar); Echo $string; /* Prints 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";} *//You can reproduce the original variable $newvar = unserialize ($string); Print_r ($newvar); /* Prints Array ([0] => Hello [1] => [2] => Array ([0] => 1 [1] => two) [3] => Apple) * * |
This is a native PHP serialization method.
However, thanks to JSON's popularity in recent years, support for JSON format has been added to PHP5.2.
Now you can use the Json_encode () and Json_decode () functions:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
A complex array $myvar = array (' Hello ', +, 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] => [2] => Array ([0] => 1 [1] => two) [3] => Apple) * * |
This will be more effective, especially if it is compatible with many other languages, such as JavaScript.
Note: For complex objects, some information may be lost.
The above mentioned is the entire content of this article, I hope you can enjoy.
Note < : More Wonderful tutorials please focus on the triple Programming