【问题标题】:How do i update an array within a cookie?如何更新 cookie 中的数组?
【发布时间】:2018-02-17 00:43:44
【问题描述】:

我在 cookie 中保存了一个购物车数组,以将其发送到购物车页面。每当我从另一个产品转到一个页面并单击添加到购物车时,它不会将其添加到数组中,但似乎会覆盖它。

$uri = $_SERVER['REQUEST_URI'];
$pin = explode('/', $uri);
$id = $pin[3]; 

$product = $model->selectById($id, 'carpet');
$product = $product->fetch(PDO::FETCH_ASSOC);

$site_url = site_url();
if(!$product){
    header("Location: $site_url./404");
}

if(isset($_POST['add'])){
    $cart = [];
    $cart[$product['id']] = [];
    $cart[$product['id']]['product_name'] = $product['name'];

    setcookie('cart', serialize($cart), time()+3600);
    $cart = unserialize($_COOKIE['cart']);
     dd($cart);
}

【问题讨论】:

  • 嗯,是的,因为这就是你告诉它要做的事情。您将$cart 定义为一个空数组,然后将产品添加到该空数组并覆盖cookie 中的任何内容。您需要从 cookie 中检索数组并将产品添加到 that 数组中。

标签: php arrays cookies


【解决方案1】:

您已经给出了答案:每次运行此脚本时,您都会覆盖购物车。变化:

$uri = $_SERVER['REQUEST_URI'];
$pin = explode('/', $uri);
$id = $pin[3]; 

$product = $model->selectById($id, 'carpet');
$product = $product->fetch(PDO::FETCH_ASSOC);

$site_url = site_url();
if(!$product){
    header("Location: $site_url./404");
}

if(isset($_POST['add'])){

    if ( isset($_COOKIE['cart']) )
         $cart = unserialize($_COOKIE['cart']); // if cookie is set, get the contents of it
    else 
         $cart = []; // else create an empty cart

    // append new product and add to cart
    $cart[$product['id']] = [];
    $cart[$product['id']]['product_name'] = $product['name'];

    setcookie('cart', serialize($cart), time()+3600);
    $cart = unserialize($_COOKIE['cart']);
     dd($cart);
}

【讨论】:

  • 谢谢!它只在我在购物车数组中添加内容后刷新页面时才有效?
  • 这是真的吗,每当我想再次将相同的产品添加到购物车中时,它不会将其添加到数组中,而是将其重叠?
  • 是的,因为您将唯一的产品 ID 作为索引。如果您想要同一产品的多个整体,则需要更改逻辑。请注意,cookie 的大小有限,最佳做法是将购物车内容存储在会话中而不是 cookie 中。
  • 嗯,product id需要保持不变,假设你在购物车中添加了1个同步,但是你想再添加5个相同的,它应该不是5而是6
  • 您是否愿意使用 Skype 聊天,了解更多关于 cookie 的问题,以及如何正确使用它们?
【解决方案2】:

问题的第二部分:如何增加产品的订购数量:

    ...
    // is this product alread in cart?
    if ( isset($cart[$product['id']])
         $prod = $cart[$product['id']]; // then pick it
    else
    {
         // create a new product object
         $prod = new stdClass();
         // initialze with name and zer quantity
         $prod->name = $product['name'];
         $prod->quantity = 0;
    }

    // increment quantity
    $prod->quantity ++;

    // reassign to array
    $cart[$product['id']] = $prod;

    ...

【讨论】:

  • 我需要在设置 cookie 的部分下面实现该代码吗?
  • 显然之前!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多