Home > php教程 > php手册 > 探讨多键值cookie(php中cookie存取数组)的详解

探讨多键值cookie(php中cookie存取数组)的详解

WBOY
Release: 2016-06-06 20:31:11
Original
1283 people have browsed it

本篇文章是对多键值cookie(php中cookie存取数组)进行了详细的分析介绍,需要的朋友参考下

cookie默认不能存数组,网站空间,所以下面的写法是错误的。
报错如下:
Warning: setcookie() expects parameter 2 to be string, array given in
但是PHP可以把同名且后面以[]结尾的cookie解析为数组。在php里面实现cookie存数组的方法如下:

方法一:先用serialize序列化数组,再存入COOKIE ,读出来时用unserialize得到原来的数组

方法二:设定多键值cookie,网站空间,香港空间,注意必须给键值

复制代码 代码如下:


$arr = array(1,2,3);
setcookie("a[0]", $arr[0]);
setcookie("a[1]", $arr[1]);
setcookie("a[2]", $arr[2]);


结果:数组所有元素都存到了。
数组长度 :3
Array ( [0] => 1 [1] => 2 [2] => 3 )

以下写法是错误的:

复制代码 代码如下:


$arr = array(1,2,3);
setcookie("a[]", $arr[0]);
setcookie("a[]", $arr[1]);
setcookie("a[]", $arr[2]);


结果:只存了最后一个元素
数组长度 :1
Array ( [0] => 3 )
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template