温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
  • 首页 > 
  • 教程 > 
  • 开发技术 > 
  • php序列化函数serialize() 和 unserialize() 与原生函数的区别是什么

php序列化函数serialize() 和 unserialize() 与原生函数的区别是什么

发布时间:2021-06-30 17:06:16 来源:亿速云 阅读:123 作者:chen 栏目:开发技术

本篇内容主要讲解“php序列化函数serialize() 和 unserialize() 与原生函数的区别是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“php序列化函数serialize() 和 unserialize() 与原生函数的区别是什么”吧!

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 等许多其他语言兼容。

注意:对于复杂的对象,某些信息可能会丢失。

到此,相信大家对“php序列化函数serialize() 和 unserialize() 与原生函数的区别是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI