[英]PHP Array Issues
我正在為朋友構建一個簡單的購物車,並在會話中使用數組來存儲它。
要將商品添加到購物車,我有此代碼
$next_item = sizeof($_SESSION['cart']) +1;
$_SESSION['cart'][$next_item] = array(item => $product_id, option => $option, qty => 1);
如果有人添加另一個相同項目或更新購物車,我在如何更新此陣列中項目的數量方面遇到的困難。 誰能指出我正確的方向? 謝謝
就像是
foreach($_SESSION['cart'] as $key => $value) {
if ($_SESSION['cart'][$key]['item'] == $product_id) {
$_SESSION['cart'][$key]['qty'] += $qty_to_add;
}
}
我會更改您的數組的結構。
代替
$_SESSION['cart'] = array(
1 => array(
'item' => 1,
'option' => 1,
'qty' => 1),
2 => array(
'item' => 2,
'option' => 1,
'qty' => 1),
3 => array(
'item' => 3,
'option' => 1,
'qty' => 1)
);
采用
$_SESSION['cart'] = array(
1 => array(
'option' => 1,
'qty' => 1),
2 => array(
'option' => 1,
'qty' => 1),
3 => array(
'option' => 1,
'qty' => 1)
);
密鑰是產品ID。 這將使引用項目更加容易,並且您可以在一行中更新數量
$_SESSION['cart'][$product_id]['qty'] += $qty_to_add;
如果訂購不重要,則可以將產品存儲在關聯數組中。
if (isset($_SESSION['cart'][$product_id])) {
// set qty of $_SESSION['cart'][$product_id] + 1
} else {
// create $_SESSION['cart'][$product_id] with qty of 1
}
首先,您不需要計算數組大小:
$_SESSION['cart'][] = array(...);
其次,我將使用$product_id
作為數組鍵。 這樣,搜索就很簡單:
if( isset($_SESSION['cart'][$product_id]) ){
$_SESSION['cart'][$product_id]['qty']++;
}else{
$_SESSION['cart'][$product_id] = array(
'option' => $option,
'qty' => 1,
);
}
我不能說您為此選擇了一個好的結構。 如何在$ product_id上建立索引呢? 這樣,您將始終知道您的購物車中是否已有特定物品:
<?php
if( isset($_SESSION['cart'][$product_id]) ) {
$_SESSION['cart'][$product_id]['qty'] += $new_qty;
} else {
$_SESSION['cart'][$product_id] = array(item => $product_id, option => $option, qty => 1);
}
?>
要將商品添加到購物車,只需使用以下命令(假設產品ID是唯一的):
$_SESSION['cart'][$product_id] = array('item' => $product_id, 'option' => $option, 'qty' => 1);
要將任何給定產品ID的數量設置為5,請使用以下命令:
$_SESSION['cart'][$product_id]['qty'] = 5;
要將產品的數量增加3,請使用以下方法:
$_SESSION['cart'][$product_id]['qty'] += 3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.