[英]the best way to store quantity in $_SESSION
我具有以下將產品添加到購物車的功能:
function AddToCart($pid)
{
$_SESSION['products'][]['product_id'] = $pid;
}
將產品數量存儲到具有產品ID的同一陣列中的最佳方法是什么,因為['products']之后的陣列會自動生成,我很困惑如何分配數量? 謝謝您的幫助:)
為什么不同時存儲您需要的所有信息? 這是我自己的購物車的摘錄:
// add item to cart
$_SESSION['cart'][] = array('product_id' => $product_id,
'cat_id' => $cat_id,
'title' => $title,
'default_img' => $default_img,
'price' => $valid_product['base_price'],
'weight' => $valid_product['weight'],
'length' => $valid_product['length'],
'width' => $valid_product['width'],
'height' => $valid_product['height'],
'surcharge' => $surcharge,
'quantity' => $quantity,
'prop_selection' => $prop_selection,
'po_id' => $po_id,
'stock' => $stock,
'shipper_id' => $valid_product['shipper_id']);
如果我正確理解了這個問題,則當為數組中已經存在的$ pid調用AddToCart()時,是否只希望它為該產品增加數量屬性? 在我看來,您只需要為$_SESSION['products']
使用關聯數組,而不是像現在這樣的數字索引數組:
function AddToCart($pid, $quantity=1) {
if(is_array($_SESSION['products']) && array_key_exists($pid, $_SESSION['products'])) {
$_SESSION['products'][$pid]['quantity'] += $quantity;
} else {
$_SESSION['products'][$pid] = array(
'product_id' => $pid,
'quantity' => $quantity
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.