浅谈php函数serialize()与unserialize()的使用方法_PHP

WBOY
Release: 2016-05-31 19:30:38
Original
1037 people have browsed it

php函数serialize():

这个函数作用就是序列化数据,返回一个可存储的字符串,该函数有利于存储或传递PHP的值,同时不丢失其类型和结构。所以我们在cms数据库里面经常看到这样的结构。

一般,我们将复杂或者数据量多而没有必要分开存储的数据封装成一个多维数组通过serialize()转成字符串,然后存进数据库,需要的时候再拿出来转成数组再用,而拿出了转成数组用的就是php的unserialize(),前面多了一个un嘛。直接上例子:
 

$a=array("周","满","和","个人","博客","www.bitsCN.com","周满和","个人博客");
$b=serialize($a);
print_r($b);
echo "<br/>";
$c=unserialize($b);
print_r($c);
Copy after login

输出结果是:

//经过serialize序列化之后得到的数据,也是存这个进数据库
a:8:{i:0;s:3:"周";i:1;s:3:"满";i:2;s:3:"和";i:3;s:6:"个人";i:4;s:6:"博客";i:5;s:20:"www.bitsCN.com";i:6;s:9:"周满和";i:7;s:12:"个人博客";}
 
//经过unserialize()反序列化得到的数据,和之前的$a数组结构一样吧
Array ( [0] => 周 [1] => 满 [2] => 和 [3] => 个人 [4] => 博客 [5] => www.bitsCN.com [6] => 周满和 [7] => 个人博客 )

Copy after login

在上一个复杂一点的二维数组的例子:

$a1=array(
  'name'=>array("周","满",'和'),
  'name_weburl'=>array("周满和","www.bitsCN.com"),
  'all'=>array('周满和个人博客'=>'www.bitsCN.com')
);
$b1=serialize($a1);
print_r($b1);
echo "<br/>";
$c1=unserialize($b1); 
print_r($c1);
Copy after login

输出结果是:

//经过serialize序列化之后得到的数据,也是存这个进数据库
a:3:{s:4:"name";a:3:{i:0;s:3:"周";i:1;s:3:"满";i:2;s:3:"和";}s:11:"name_weburl";a:2:{i:0;s:9:"周满和";i:1;s:20:"www.bitsCN.com";}s:3:"all";a:1:{s:21:"周满和个人博客";s:20:"www.bitsCN.com";}}
 
//经过unserialize()反序列化得到的数据,和之前的$a数组结构一样吧
Array ( [name] => Array ( [0] => 周 [1] => 满 [2] => 和 ) [name_weburl] => Array ( [0] => 周满和 [1] => www.bitsCN.com ) [all] => Array ( [周满和个人博客] => www.bitsCN.com ) )
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template