注:a代表array,s代表string,b代表bool,i代表int,数字代表个数/长度
序列化:
serialize() 用于序列化对象或数组,并返回一个字符串。
实例
:
<?php
$sites = array('Google', 'Runoob', 'Facebook');
$serialized_data = serialize($sites);
echo $serialized_data . PHP_EOL;
?>
输出结果为:
a:3:{i:0;s:6:"Google";i:1;s:6:"Runoob";i:2;s:8:"Facebook";}
序列化格式:
在PHP中,序列化用于存储或传递 PHP 的值的过程中,同时不丢失其类型和结构。
序列化函数原型如下:
string serialize ( mixed $value )
先看下面的例子:
class CC {
public $data;
private $pass;
public function __construct($data, $pass)
{
$this->data = $data;
$this->pass = $pass;
}
}
$number = 34;
$str = 'uusama';
$bool = true;
$null = NULL;
$arr = array('a' => 1, 'b' => 2);
$cc = new CC('uu', true);
var_dump(serialize($number));
var_dump(serialize($str));
var_dump(serialize($bool));
var_dump(serialize($null));
var_dump(serialize($arr));
var_dump(serialize($cc));
输出结果为:
string(5) "i:34;"
string(13) "s:6:"uusama";"
string(4) "b:1;"
string(2) "N;"
string(30) "a:2:{s:1:"a";i:1;s:1:"b";i:2;}"
string(52) "O:2:"CC":2:{s:4:"data";s:2:"uu";s:8:" CC pass";b:1;}"
所以序列化对于不同类型得到的字符串格式为:
String : s:size:value;
Integer : i:value;
Boolean : b:value;(保存1或0)
Null : N;
Array : a:size:{key definition;value definition;(repeated per element)}
Object : O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}
反序列化:
unserialize() 用于将通过serialize()函数序列化后的对象或数组进行反序列化,并返回原始的对象结构。
实例
:
<?php
$str = 'a:3:{i:0;s:6:"Google";i:1;s:6:"Runoob";i:2;s:8:"Facebook";}';
$unserialized_data = unserialize($str);
print_r($unserialized_data);
?>
输出结果为:
Array
(
[0] => Google
[1] => Runoob
[2] => Facebook
)
eg:a:3{i:0;s:6:"Google";i:1;s:6:"Runoob";i:2;s:8:"Facebook";}
a:3 a数组中3个元素
i:0 数组中下标为0元素
s:6:"Google" 字符串Google长度为6
i:1 数组中下标为1元素
s:6:"Runoob" 字符串Runoob长度为6
i:2 数组中下标为2元素
s:8:"Facebook" 字符串Facebook长度为8