[英]Multiple items in a PHP shopping cart
我正在用PHP制作購物車。 為了檢查用戶是否選擇了多個產品,我將所有內容放入一個數組($ contents)。 輸出時,會得到類似“ 14,14,14,11,10”的信息。 我想輸入類似“ 3 x 14、1 x 11、1 x 10”的文字。 最簡單的方法是什么? 我真的不知道該怎么做。
這是我的代碼中最重要的部分。
$_SESSION["cart"] = $cart;
if ( $cart ) {
$items = explode(',', $cart);
$contents = array();
$i = 0;
foreach ( $items as $item ) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
$i++;
}
$smarty->assign("amount",$i);
echo '<pre>';
print_r($contents);
echo '</pre>';
提前致謝。
為什么不構建一個更強大的購物車實施方案?
考慮從這樣的數據結構開始:
$cart = array(
'lines'=>array(
array('product_id'=>14,'qty'=>2),
array('product_id'=>25,'qty'=>1)
)
);
或類似。
然后,您可以創建在購物車結構上運行的一組函數:
function addToCart($cart, $product_id, $qty){
foreach($cart['lines'] as $line){
if ($line['product_id'] === $product_id){
$line['qty'] += $qty;
return;
}
}
$cart['lines'][] = array('product_id'=>product_id, 'qty'=>$qty);
return;
}
當然,您可以(也許應該)走得更遠,並將此數據結構和功能組合到一組類中。 購物車是以面向對象的方式開始精簡的好地方。
內置的array_count_values函數可以完成此任務。
例如:
<?php
$items = array(14,14,14,11,10);
var_dump(array_count_values($items));
?>
輸出:
array(3) {
[14]=>
int(3)
[11]=>
int(1)
[10]=>
int(1)
}
您將受益於使用多維數組將數據存儲在更健壯的結構中。
例如:
$_SESSION['cart'] = array(
'lines'=>array(
array('product_id'=>14,'quantity'=>2, 'item_name'=>'Denim Jeans'),
...
)
);
然后,要將新項目添加到購物車中,您只需執行以下操作:
$_SESSION['cart'][] = array('product_id'=45,'quantity'=>1, 'item_name'=>'Jumper');
當您讓用戶添加項目時,您需要將其添加到數組中的正確位置。 如果產品ID已存在於陣列中,則需要對其進行更新。 此外,請始終注意嘗試輸入零或負數的用戶!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.