PHP MySQL 购物车使用 2D 数组更新商品的数量


php mysql shopping cart updating quantity of an item using 2d array

我正在构建的购物车似乎只更新了数组第一个元素的数量。因此,例如,我的购物车中的第一项商品的数量为 1,然后当我从产品页面添加另一个数量 2 时,总数将变为 3,这就是我想要的。但是,如果我对另一个项目重复这些步骤,它会将它们单独添加到数组中,而不是将它们分组在一起

if(isset($_GET['add'])){
foreach ($_SESSION['cart'] as $key => $item){
            if ($item['id'] == $itemID) {
                $newQuan = $item['quantity'] + $quantity;
                unset($_SESSION['cart'][$key]);
                $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $newQuan);
                header('Location:xxx');//stops user contsanlty adding on refresh
                exit;
            }
            else{
                $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
                header('xxx');//stops user contsanlty adding on refresh
                exit;
            }
        }
    }

谁能帮我解决为什么第一个元素只更新

你的问题是foreach循环中的其他情况。第一个项目由 if 检查,然后 - 当第一个项目不匹配时 - else 案例激活并添加新项目。

else{
            $_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
            header('xxx');//stops user contsanlty adding on refresh
            exit;
        }

您要做的是检查整个购物车,然后 - 如果未找到文章 - 将其添加到购物车中。为此,我建议使用一个变量来检查您是否在循环中找到了条目。为了获得灵感,我插入了下面的代码。只需要进行微小的更改:添加 found-variable 并初始化它(未找到),将变量设置为在 if case 中找到,并在退出 foreach-loop 后检查变量是否已设置(如果不是,您确定要添加商品到购物车)。

$foundMyArticle = 0;
foreach ($_SESSION['cart'] as $key => $item){
        if ($item['id'] == $itemID) {
            $foundMyArticle = 1;
            ... THE OTHER CODE
} //end of the foreach
if($foundMyArticle == 0)
{ //COPY THE CODE FROM THE ELSE-CASE HERE }

我还没有测试过它,但这可能更简单一些:

if(isset($_GET['add']))
{
    if(!isset($_SESSION['cart'])) $_SESSION['cart'] = array();
    if(!isset($_SESSION['cart'][$itemID]))
    {
        $_SESSION['cart'][] = array('id' => $itemID, 'quantity' => $quantity);
    }
    else
    {
        $_SESSION['cart'][$itemID]['quantity'] += $quantity;
    }
}

首先,问题和代码似乎不够清晰,但我会尽力提供我认为可能会有所帮助的建议(我会做一些假设)。

这些变量从何而来?

$itemID, $quantity
假设

他们是在$_GET,我会说最好像这样保存您的购物车信息:

$itemCartIndex = strval($itemID);
//convert the integer item id to a string value -- or leave as string if already a string
$currentQuantity = (isset($_SESSION["cart"][$itemCartIndex]))? intval($_SESSION["cart"][$itemCartIndex]["quantity"]):0;
//set it by default if the index does not exist in the cart already
$currentQuantity += $quantity;
//update the quantity for this particular item
$_SESSION["cart"][$itemCartIndex] = array("quantity"=>$currentQuantity,...,"price"=>12.56);
//set up the index for this item -- this makes it easy to remove an item from the cart
//as easy as unset($_SESSION["cart"][$itemCartIndex]

完成此操作后,向所有者展示/展示购物车是微不足道的。

祝你好运