Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用cookies方法将多个项目添加到购物车_Php - Fatal编程技术网

Php 如何使用cookies方法将多个项目添加到购物车

Php 如何使用cookies方法将多个项目添加到购物车,php,Php,当我将第二个项目添加到购物车时,第一个项目将被替换 这是我的代码(cart.php) 购物车更新页面如下所示 <?php class CartUpdate { /** * Initialize the Cart. * @return void */ public function __construct() { if(isset($_COOKIE['cart'])) { $cookie = $

当我将第二个项目添加到购物车时,第一个项目将被替换
这是我的代码(cart.php)


购物车更新页面如下所示

<?php
class CartUpdate 
{

    /**
     * Initialize the Cart.
     * @return void
     */
    public function __construct() {

        if(isset($_COOKIE['cart'])) {

            $cookie = $_COOKIE['cart'];
            $cookie = stripslashes($cookie);
            $savedCardArray = json_decode($cookie, true);

         }
    }


    function add()
    {
        $variety = test_input($_POST["variety"]);  
        $rice_type = test_input($_POST["rice_type"]);
        $quantity = test_input($_POST["quantity"]);
        $bran = test_input($_POST["bran"]);
        $items[]=array($variety,$quantity,$bran,$rice_type);
        $json = json_encode($items);    
        setcookie('cart', $json);
    }

我的PHP最近有些生疏,但似乎每次调用Cart对象上的add()方法时,都会重写cookie。在购物车构造函数中,您将cookie内容读入本地var
$savedCardArray
(输入错误?),然后在add()方法中操作本地var
$items
,向其中添加新元素并保存cookie


我建议重构这段代码。首先,这个类被称为CartUpdate有什么特殊的原因吗?只要把它命名为购物车。在构造函数中,将cookie读入实例变量,这样一旦从cookie中读取了内容,就可以在Cart实例的其他方法中访问它。您还可以提供get()方法来返回购物车中的商品数组,以及total()方法来计算总价。

很抱歉没有编辑您的代码,我已经很久没有使用PHP了,不想通过查找来获得正确的语法:)我更新了我的答案,让您有更多的了解。
<?php
class CartUpdate 
{

    /**
     * Initialize the Cart.
     * @return void
     */
    public function __construct() {

        if(isset($_COOKIE['cart'])) {

            $cookie = $_COOKIE['cart'];
            $cookie = stripslashes($cookie);
            $savedCardArray = json_decode($cookie, true);

         }
    }


    function add()
    {
        $variety = test_input($_POST["variety"]);  
        $rice_type = test_input($_POST["rice_type"]);
        $quantity = test_input($_POST["quantity"]);
        $bran = test_input($_POST["bran"]);
        $items[]=array($variety,$quantity,$bran,$rice_type);
        $json = json_encode($items);    
        setcookie('cart', $json);
    }