php序列化函数数组与对象的方法

php序列化函数数组与对象的方法

时间:2015-12-17 14:48:44 来源:网络
导读:php格式化字符串并转换成数组或对象,php序列化处理的方法,在php中序列化变量的方法。
 

转自:http://www.xfcodes.com/php/shili/1730.htm

 

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'
); // www.xfcodes.com

// 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 等许多其他语言兼容。
注意:对于复杂的对象,某些信息可能会丢失。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值