[英]Delete value in cookie array
我有一个像这样的json项的cookie数组
//set my cookie
setcookie("my_Cookie", $cookie_content, time()+3600);
//this is the content of my cookie for example with 2 items
[{"item_id":"9","item_tag":"AS","session_id":"554obe5dogsbm6l4o9rmfif4o5"},{"item_id":"6","item_tag":"TE","session_id":"554obe5dogsbm6l4o9rmfif4o5"}]
工作流程就像一个购物车,我可以添加和删除项目。 我网站上的一个“产品”包含:item_id,item_tag和session_id;
对于添加项目,cookie将扩展为item_id“:” X“,” item_tag“:” X“,” session_id“:” X
现在,如果我单击删除,我想删除cookie中的当前三个值
我尝试
未设置($ _COOKIE [“ my_Cookie”,'item_id'=> $ item_id,'item_tag'=> $ item_tag,'session_id'=> $ session_id]); 但这不起作用
是否可以删除Cookie的特定值?
像这样:
setcookie('cookie_name'); // Deletes the cookie named 'cookie_name'.
之所以可行,是因为将Cookie设置为无值与删除Cookie相同。
如果我没记错的话,您将无法直接修改Cookie的值; 您将必须读取值,进行任何修改,然后使用相同的名称替换cookie。
因此,在这种情况下,一旦用户点击了删除链接,您的脚本应保存他们要删除的项目的ID,读取Cookie值,重写数组,然后将Cookie替换为更新后的值。
也许这个演示会有所帮助:
// Should be the user submitted value to delete.
// Perhaps a $_GET or $_POST value check.
$value_to_delete = 9;
// Should be the cookie value from $_COOKIE['myCookie'] or whatever the name is.
// Decode from JSON values if needed with json_decode().
$cookie_items = array(
array("item_id" => 9, "item_tag" => "RN"),
array("item_id" => 6, "item_tag" => "RN"),
array("item_id" => 4, "item_tag" => "RN")
);
// Run through each item in the cart
foreach($cookie_items as $index => $value)
{
$key = array_search($value_to_delete, $value);
if($key == "item_id")
{
unset($cookie_items[$index]);
}
}
// Reset the index
$cookie_items = array_values($cookie_items);
// Set the cookie
setcookie($cookie_items);
// Debug to view the set values in the cookie
print_r($cookie_items);
我相信Cookie只会以字符串形式存储,因此最好将其覆盖...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.