7、序列化
你有没有遇到过需要在数据库或文本文件存储一个复杂变量的情况?你可能没能想出一个格式化字符串并转换成数组或对象的好方法,PHP 已经为你准备好此功能。有两种序列化变量的流行方法。下面是一个例子,使用 serialize() 和 unserialize() 函数:
// a complex array $myvar = array( 'hello', 42, 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] => 42 [2] => Array ( [0] => 1 [1] => two )
[3] => apple ) */
这是原生的 PHP 序列化方法。然而,由于 JSON 近年来大受欢迎,PHP5.2 中已经加入了对 JSON 格式的支持。现在你可以使用 json_encode() 和 json_decode() 函数:
// 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 ) */
这将更为行之有效,尤其与 JavaScript 等许多其他语言兼容。然而对于复杂的对象,某些信息可能会丢失。
出处:蓝色理想
责任编辑:bluehearts
上一页 9个必须知道的实用PHP函数和功能 [3] 下一页 9个必须知道的实用PHP函数和功能 [5]
◎进入论坛网络编程版块参加讨论
|