我试图创建一个将商品添加到购物车的php函数。 我希望它做的是检查数组以查看该物品是否已在那里,是否增加了数量,如果没有在购物车中创建该物品。
相反,它正在做的是添加一个项目,它将在第一次工作(如果项目已经存在,它只会增加数量),但如果你添加另一个项目,它会继续在购物车中创建该项目的新实例例如
项目 1 - 数量 4项目 2 - 数量 1项目 2 - 数量 1项目 2 - 数量 1...等等...
以下是我到目前为止的代码?
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
$i=0;
while($added == false)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
//$i++;
//break;
}
if($added == true)
{
break;
}
else //if($added == false)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
$added = true;
//break;
}
//else break;
$i++;
}
}
else
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
问题是您没有首先搜索整个数组以查看其中是否存在该项。 下面的代码应该可以工作,但我可能犯了一个错别字或其他东西,所以一定要仔细检查它。
function add_item ($id, $qty)
{
$count=$this->countItems;
echo "uytfdgghjkl;kj<br>";
$added = false;
if($count>0)
{
for($i=0; $i < $count; $i++)
{
echo "fghjkl<br>";
$tid = $this->items[$i]->getId();
echo "new ID: ".$tid."<br>";
echo "old ID: ".$id."<br>";
echo $i;
if($tid == $id)
{
$amount = $this->items[$i]->getQty();
$this->items[$i]->setQty($amount+1);
$added = true;
break;
}
}
}
if(!$added)
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
//$this->total = $total+ ($qty *$price);
$this->countItems++;
}
}
更好的选择是使用字典
即。
$arr = array();
$arr['item_id'] = new OrderItem(...);
然后,您可以使用以下命令检查该项目是否在数组中:
if(isset($arr[$id])){
...
}
逻辑有缺陷。仅当商品恰好是购物车中的第一件商品时,代码才会增加商品的数量。否则,它将添加该项目。这里证明:
if($added == true) // if this cart item's quantity was incremented
{
break;
}
else // add item
{
$this->items[$this->countItems] = new OrderItem($id, $qty);
// etc...
}
相反,您应该从循环中删除new OrderItem($id, $qty)
,并在循环遍历所有购物车项目后检查$added
的值。为此,您需要使用 $count
循环通过for
(而不是一段时间)。
类产品扩展CI_Controller{
function __construct(){
parent::__construct();
// Load cart library
$this->load->library('cart');
// Load product model
$this->load->model('product');
}
function index(){
$data = array();
// Fetch products from the database
$data['products'] = $this->product->getRows();
// Load the product list view
$this->load->view('products/index', $data);
}
function addToCart($proID){
// Fetch specific product by ID
$product = $this->product->getRows($proID);
// Add product to the cart
$data = array(
'id' => $product['id'],
'qty' => 1,
'price' => $product['price'],
'name' => $product['name'],
'image' => $product['image']
);
$this->cart->insert($data);
// Redirect to the cart page
redirect('cart/');
}
}