使用更多变体更新购物车


Update shopping cart with more variants

我目前正在尝试创建购物车并通过$_SESSION变量发送它。

但当我尝试通过$_POST更新商品时,它只更新购物车中的最后一个产品。

这是我的表格

<form method="post">
<?php foreach ($_SESSION['cart'] as $product) { 
$productDetail = Products::getProduct($product['id']);
?>
<input type="hidden" name="id" value="<?= $product['id']; ?>">
<input name="qty" size="5" maxlength="50" type="text" value="<?= $product['quantity']; ?>">
<input name="width" size="5" maxlength="50" type="text" value="<?= $product['width']; ?>">
<input name="length" size="5" maxlength="5" type="text" value="<?= $product['length']; ?>">
<?php } ?>
<input type="submit" value="send" />
</form>

以下是我如何更新我的购物车

$item_id = $data['id'];
$quantity = $data['qty'];
$width = $data['width'];
$length = $data['length'];
$_SESSION['cart'][$item_id]['quantity'] = $quantity;
$_SESSION['cart'][$item_id]['width'] = $width;
$_SESSION['cart'][$item_id]['length'] = $length;

它总是只更新表单中的最后一个。

这个问题有没有更好的解决方案?我非常感谢。

谢谢。

您需要将[]添加到输入名称中才能获得$_POST值中的数组:

<form method="post">
<?php foreach ($_SESSION['cart'] as $product) { 
$productDetail = Products::getProduct($product['id']);
?>
<input type="hidden" name="id[]" value="<?= $product['id']; ?>">
<input name="qty[]" size="5" maxlength="50" type="text" value="<?= $product['quantity']; ?>">
<input name="width[]" size="5" maxlength="50" type="text" value="<?= $product['width']; ?>">
<input name="length[]" size="5" maxlength="5" type="text" value="<?= $product['length']; ?>">
<?php } ?>
<input type="submit" value="send" />
</form>

然后,您可以迭代$data['id']数组(我在这里假设它与$_POST['id']相同),利用这4个数组对给定数据集具有相同的对应密钥的事实:

$item_ids = $data['id'];
$quantitys = $data['qty'];
$widths = $data['width'];
$lengths = $data['length'];
foreach($item_ids as $k=>$item_id){
    $_SESSION['cart'][$item_id]['quantity'] = $quantitys[$k];
    $_SESSION['cart'][$item_id]['width'] = $widths[$k];
    $_SESSION['cart'][$item_id]['length'] = $lengths[$k];
}