首页 > 解决方案 > 我无法将多个产品添加到我的 PHP 购物车

问题描述

我想使用 PHP 将带有产品信息的多个产品添加到购物车页面,但我不能。我的第一个产品已添加,但随后无法正常工作。

我的代码是:

<?php

session_start();
// session_destroy();

// Add to Cart
if (isset($_POST["add_to_cart"])) {
    $name = $_POST["name"];
    $price = $_POST["price"];
    $quantity = $_POST["quantity"];
    $stock = $_POST["stock"];

    if ($stock >= $quantity) {
        if (isset($_SESSION["cart"])) {
            $cart_item = array(
                'p_name' => $name, 
                'p_price' => $price, 
                'p_quantity' => $quantity, 
                'p_stock' => $stock,
            );
            $new_item = array_merge($_SESSION["cart"], $cart_item);
            $_SESSION["cart"] = $new_item;
            print_r($_SESSION["cart"]);
        } else {
            $cart_item = array(
                'p_name' => $name, 
                'p_price' => $price, 
                'p_quantity' => $quantity, 
                'p_stock' => $stock,
            );
            $_SESSION["cart"] = $cart_item;
            print_r($_SESSION["cart"]);
        }
    } else {
        
    }
} else {
    print_r($_SESSION["cart"]);
}

?>

标签: php

解决方案


我已经更改了代码以增加可读性和功能。我所做的主要事情是确定没有创建多维数组,这是问题的根源。

$cart_item = array(
   'p_name' => $name, 
   'p_price' => $price, 
   'p_quantity' => $quantity, 
   'p_stock' => $stock,
);
$_SESSION["cart"] = $cart_item;

那只会给你一个单一的产品。我已经改变了它,所以它将是一个贯穿始终并且可以包含许多产品的阵列。

<?php
session_start();
// session_destroy();

// Add to Cart
if (isset($_POST["add_to_cart"])) {
    $name = $_POST["name"];
    $price = $_POST["price"];
    $quantity = $_POST["quantity"];
    $stock = $_POST["stock"];

    // Pull the array (if it exists into a variable)
    $cart = $_SESSION['cart'];
    if (!isset($cart)) {
        // Define the cart as an array
        $cart = [];
    }

    if ($stock >= $quantity) {
        // Push the product into the array of cart items
        $cart[] = [
            'p_name' => $name,
            'p_price' => $price,
            'p_quantity' => $quantity,
            'p_stock' => $stock,
        ];
        // Set the cart to the $_SESSION
        $_SESSION["cart"] = $cart;
        print_r($_SESSION["cart"]);
    } else {
        // Should probably do something here
        echo "We are out of stock.";
    }
} else {
    if (isset($_SESSION['cart'])) {
        print_r($_SESSION["cart"]);
    }
}

推荐阅读