简体   繁体   English

删除Cookie数组中的值

[英]Delete value in cookie array

I have an cookie array with json items like this 我有一个像这样的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"}]

The workflow is like an shopping cart, I can add and delete items. 工作流程就像一个购物车,我可以添加和删除项目。 One "product" on my website contains: item_id, item_tag and the session_id; 我网站上的一个“产品”包含:item_id,item_tag和session_id;

For adding an item the cookie will be extended with item_id":"X","item_tag":"X","session_id":"X 对于添加项目,cookie将扩展为item_id“:” X“,” item_tag“:” X“,” session_id“:” X

now if I click on delete I want remove the current three values in the cookie 现在,如果我单击删除,我想删除cookie中的当前三个值

I try it with 我尝试

unset($_COOKIE["my_Cookie", 'item_id'=> $item_id, 'item_tag'=> $item_tag, 'session_id'=> $session_id]); 未设置($ _COOKIE [“ my_Cookie”,'item_id'=> $ item_id,'item_tag'=> $ item_tag,'session_id'=> $ session_id]); but this doesn't work 但这不起作用

Is it possible to delete specific values of my cookie? 是否可以删除Cookie的特定值?

Like this: 像这样:

setcookie('cookie_name'); // Deletes the cookie named 'cookie_name'.

This works because setting a cookie with no value is the same as deleting it. 之所以可行,是因为将Cookie设置为无值与删除Cookie相同。

If I'm not mistaken, you can't directly modify a cookie's value; 如果我没记错的话,您将无法直接修改Cookie的值; you'll have to read the value, make any modifications, and then replace the cookie using the same name. 您将必须读取值,进行任何修改,然后使用相同的名称替换cookie。

So, in this case, once a user hits the delete link, your script should save the ID of the item that they want removed, read the cookie value(s), rewrite the array and then replace the cookie with the updated values. 因此,在这种情况下,一旦用户点击了删除链接,您的脚本应保存他们要删除的项目的ID,读取Cookie值,重写数组,然后将Cookie替换为更新后的值。

Perhaps this demo will help: 也许这个演示会有所帮助:

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM