【问题标题】:Delete value in cookie array删除 cookie 数组中的值
【发布时间】:2012-11-16 15:54:21
【问题描述】:

我有一个带有像这样的 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 的特定值?

【问题讨论】:

    标签: php arrays cookies shopping-cart


    【解决方案1】:

    像这样:

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

    这是可行的,因为设置一个没有值的 cookie 与删除它是一样的。

    【讨论】:

      【解决方案2】:

      如果我没记错的话,你不能直接修改 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);
      

      【讨论】:

      • 并且可以通过未设置删除数组的当前值? $key = array_search($deletethisvalues,$array); if($key!==false){ unset($array[$key]); }
      【解决方案3】:

      我相信一个 cookie 会简单地存储为一个字符串,所以你最好只是覆盖它......

      【讨论】:

      • 是的,cookie 值存储为字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多