通常在数据库中存储数组时会发生什么?
尝试在数据库中注册以下数组。
[ student1 , student2 , student3 ]
然后尝试再次获取它
Array( student1 , student2 , student3 )
我们获取到的是字符串,在没有序列化的情况下在数据库中注册后,如果再次检索它,它将成为一个字符串。
使用foreach语句获取此字符串是不行的。
数组需要作为数组在数据库中注册,这时就需要使用序列化。
我们来使用一下序列化
要序列化,需要使用serialize函数
此外,结果取决于要序列化的数据类型。
序列化数组
?php$test = [ student1 , student2 , student3 $disp = serialize($test);echo $disp;
执行结果为
a:3:{i:0;s:8: student1 i:1;s:8: student2 i:2;s:8: student3 }
请注意,初始[a:3]部分以[type:html' target='_blank'>value]的形式显示。
表示数组的类型是a。
此外,之后的显示是数组数据部分,由[key; value;]表示
序列化整数
?php$test = 50;$disp = serialize($test);echo $disp;
结果为
i:50;
序列化字符串
?php$test = student $disp = serialize($test);echo $disp;
结果为
s:7: student
表示字符串的类型是s。
在字符串的情况下也有数字,但这表示字符数。
序列化很简单。
然后发送序列化数据或将其保存在数据库中。
用unserialize进行反序列化
要使用序列化数据,您不能按原样使用它。
必须使用 unserialize来恢复原始类型和结构。
反序列化数组
?php$test = [ student1 , student2 , student3 $disp = serialize($test);echo $disp;echo br / echo print_r(unserialize($disp));
为了清晰起见,显示了序列化的$ disp,并设置换行符( br / )。
此外,$ disp被反序列化并显示。
print_r用于显示数组的内容。
结果为
a:3:{i:0;s:8: student1 i:1;s:8: student2 i:2;s:8: student3 }Array ( [0] = student1 [1] = student2 [2] = student3 )1
第一行是序列化的结果,第二行是反序列化的结果。
反序列化整数
?php$test = 50;$disp = serialize($test);echo $disp;echo br / echo unserialize($disp);
结果为
i:50;50
反序列化字符串
?php$test = student $disp = serialize($test);echo $disp;echo br / echo unserialize($disp);
结果为
s:7: student student
恢复序列化数据很容易。
以上就是php序列化的用法总结(代码示例)的详细内容,PHP教程
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答