开发者

How to assign multiple dimensional array in cookies with PHP?

cookie[person][name],  cookie[person][id],  cookie开发者_C百科[person][age]

How to make the cookie like above?


Well, you could assign the value of the cookie to be a serialized array

$array = array("person1" => array("name" => "Ted"));
$value = serialize($array);
set_cookie("name", $value);

When you want to read it back, get the data from the cookie and unserialize it

$array = unserialize($_COOKIE['name']);

That probably wouldn't hide the data you are trying to store very well. The other situation is to use a Session variable instead

session_start();

Now you can assign anything you want, arrays, objects, anything to $_SESSION.

$_SESSION['person'] = array();

The session variable is very similar to an array, but the data is actually stored in a file, and the id of the user is stored in a cookie. PHP matches the ID on the cookie with the file, and when you hit session_start(), populates the superglobal with the files contents.

This means that objects you make will end up being serialized.

Either way, it is the same basic idea. You serialize a data structure, write it to a file (cookie or session file) and read it back later.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜