Most of the time, we need to store complex arrays in a database or in a file in PHP. Some people may use PHP built-in functions to accomplish this task. A complex array is an array that has elements of multiple data types or arrays.
However, we already have a convenient solution to handle this situation. We don't have to write our own function to convert complex arrays into formatted strings. There are two popular methods of variable serialization. (Recommended: PHP Tutorial)
1、serialize()
2、unserialize()
We can use the serialize() function to serialize any data in PHP. The serialize() function accepts a parameter, which is the data we want to classify and returns a serialized string.
The program is as follows:
<?php //一个复杂的数组 $myvar = array( 'hello', 42, array(1, 'two'), 'apple' ); // 转换成字符串 $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";}
From the above code, we get a variable $string with serialized data. We can use the unserialize() function to deserialize the value of a variable to return the original value of the complex array $myvar.
serialize() and unserialize() function example:
<?php // 一个复杂的数组 $myvar = array( 'hello', 42, array(1, 'two'), 'apple' ); // 序列化上述数据 $string = serialize($myvar); // 反序列化$string中的数据 $newvar = unserialize($string); // 打印未序列化的数据 print_r($newvar); ?>
Output:
Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple )
This is the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can serialize and deserialize data in PHP using json_encode() and json_decode() functions respectively.
Since the JSON format is text only, it can be easily sent to or from the server and can be used as a data format by any programming language.
Let’s see how to use json_encode() in PHP :
<?php // 一个复杂的数组 $myvar = array( 'hello', 42, array(1, 'two'), 'apple' ); // 序列化数据 $string = json_encode($myvar); // 打印序列化的数据 echo $string; ?>
Output:
["hello",42,[1,"two"],"apple"]
We can use json_decode() Function decodes the data encoded in the above program to obtain the original complex array.
The program is as follows:
<?php // 一个复杂的数组 $myvar = array( 'hello', 42, array(1, 'two'), 'apple' ); // 序列化数据 $string = json_encode($myvar); // 解码上面编码的字符串 $newvar = json_decode($string); // 打印解码后的数据 print_r($newvar); ?>
Output:
Array ( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple )
The above is the detailed content of How does PHP serialize data?. For more information, please follow other related articles on the PHP Chinese website!