php中有格式化字符串并转换成数组或对象的好方法,即序列化处理。
有两种序列化变量的方法。
以下示例,使用 serialize() 和 unserialize() 函数:
// a complex array $myvar = array( 'hello', 42, array(1,'two'), 'apple' ); // convert to a string $string = serialize($myvar); echo $string; // you can reproduce the original variable $newvar = unserialize($string); print_r($newvar);
这是原生的 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; // you can reproduce the original variable $newvar = json_decode($string); print_r($newvar);
这将更为行之有效,尤其与 Javascript 等许多其他语言兼容。
注意:对于复杂的对象,某些信息可能会丢失。
以上所述就是本文的全部内容了,希望大家能够喜欢。



