簡體   English   中英

刪除Cookie數組中的值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM