php序列化函数serialize() 和 unserialize() 与原生函数对比
php中有格式化字符串并转换成数组或对象的好方法,即序列化处理。
有两种序列化变量的方法。
以下示例,使用serialize()和unserialize()函数:
//acomplexarray
$myvar=array(
'hello',
42,
array(1,'two'),
'apple'
);
//converttoastring
$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";}
*/
//youcanreproducetheoriginalvariable
$newvar=unserialize($string);
print_r($newvar);
/*prints
Array
(
[0]=>hello
[1]=>42
[2]=>Array
(
[0]=>1
[1]=>two
)
[3]=>apple
)
*/
这是原生的PHP序列化方法。
然而,由于JSON近年来大受欢迎,PHP5.2中已经加入了对JSON格式的支持。
现在你可以使用json_encode()和json_decode()函数:
//acomplexarray $myvar=array( 'hello', 42, array(1,'two'), 'apple' ); //converttoastring $string=json_encode($myvar); echo$string; /*prints ["hello",42,[1,"two"],"apple"] */ //youcanreproducetheoriginalvariable $newvar=json_decode($string); print_r($newvar); /*prints Array ( [0]=>hello [1]=>42 [2]=>Array ( [0]=>1 [1]=>two ) [3]=>apple ) */
这将更为行之有效,尤其与JavaScript等许多其他语言兼容。
注意:对于复杂的对象,某些信息可能会丢失。
以上所述就是本文的全部内容了,希望大家能够喜欢。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下