我正在嘗試更新陣列中的特定會話變數。
我如何設定會話
$_SESSION['cart_items'][] = [
'size' => $size,
'color' => $color,
'qty' => $quantity,
'price' => $price,
'productId' => $productId,
'image' => $image,
'name' => $name,
];
當我在表格中按更新時,我想更新“數量”。
foreach ($_SESSION["cart_items"] as $key => $item) {
$item_price = $item["qty"] * $item["price"];
$total_quantity = $item["qty"];
$item_total = $item_price * $total_quantity;
$total_price = ($item["price"] * $item["qty"]);
$_SESSION['totalprice'] = $total_price;
//html code
echo '
<div >
<div id="cartimage">
<img src=' . $item['image'] . '>
</div>
<div id="cartdesc">
<form method="get" action="cart.php">
<p id="cartitemname"> ' . $item["name"] . ' </p>
<p>Quantity: <input id="updateprice" name="updateprice" type="number" step="1" min="1" value="' . $item["qty"] . '"> </p>
<p>Size: ' . $item["size"] . ' </p>
<p>Price:$ ' . $item["price"] . ' </p>
<p>Item total price $ ' . number_format($item["qty"] * $item["price"], 2) . ' </p>
<button type="submit" name="update">Update</button>
<a href="cart.php?action=remove&code=' . $key . '" ><img id="deletebtn" src="res/istockphoto-928418914-170667a.jpg" alt="更新購物車中的會話變數" /></a>
</form>
</div>
</div>
';
}
當我按下更新時呼叫的 get 方法:
if (isset($_GET['update'])) {
//print_r($_SESSION["cart_items"]);
// what i have tried :
// $_SESSION['cart_items']['qty'] = $_GET['updateprice']
//$item["qty"] = $_GET['updateprice'];
header('location:cart.php');
}
這兩個都不行!任何幫助或朝著正確方向輕推將不勝感激!
uj5u.com熱心網友回復:
問題在于如何將商品添加到購物車。您只是將它們推入索引陣列,這使得添加后很難參考特定的購物車專案。
演示:
// Equal to how you add the cart items
$array[] = [
'id' => 1,
'qty' => 1
];
$array[] = [
'id' => 2,
'qty' => 1
];
// Results in an indexed array like this:
[
0 => [
'id' => 1,
'qty' => 1
],
1 => [
'id' => 1,
'qty' => 1
]
]
為了能夠更新其中任何一個,您需要執行以下操作:
// The first
$array[0]['qty'] = 2;
// The second
$array[1]['qty'] = 2;
這使得它更難,因為您需要知道添加購物車專案的索引。除非您想遍歷購物車并檢查每個專案是否是您要更改的專案。
一種解決方案是改用關聯陣列,在其中設定陣列鍵:
$array['someIdentifier] = [
'id' => 1,
'qty' => 1
];
// Results in
[
'someIdentifier' => [
'id' => 1,
'qty' => 1
]
]
現在您可以使用識別符號專門訪問它
$array['someIdentifier']['qty'] = 2;
識別符號可能應該是產品特定變體的唯一識別符號,例如尺寸、顏色等,因為您可以為同一產品擁有不同的購物車專案,但具有不同的變體。
在電子商務系統中,每個變體(或庫存單位 (SKU))通常都有一個唯一識別符號,這將是一個很好的識別符號。您應該如何設定它們取決于您的應用程式。如果您考慮是否應該能夠更改現有尺寸、顏色等,它會變得有點復雜。然后,您需要洗掉先前變體的舊購物車專案并添加新的。
希望它能澄清一些事情。
uj5u.com熱心網友回復:
解決方案!!基于 M. Eriksson 的建議
理想情況下,資料庫中應該有一個唯一的識別符號。使用它并替換我在這里寫的'uniquekey'。我沒有唯一鍵,因此使用以下方法。
在 html 表單端,
<input type="hidden" name="uniquekey" id="uniquekey">
使用JS生成唯一鍵:
<script>
var key = Math.random()
document.getElementById("uniquekey").value = key
</script>
添加了一個額外的識別符號,唯一鍵
$_SESSION['cart_items'][$uniquekey] = [
'uniquekey' => $uniquekey,
'size' => $size,
'color' => $color,
'qty' => $quantity,
'price' => $price,
'productId' => $productId,
'image' => $image,
'name' => $name,
];
現在,您可以識別陣列中的特定條目了!
if (isset($_GET['update'])) {
$_SESSION["cart_items"][$_GET['uniquekey']]['qty'] = $_GET['updateprice'];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527730.html
標籤:php会议
