[英]Array item could not be found in php shopping cart
我在PHP數組中遇到一種奇怪的情況。 我正在嘗試使用會話變量創建一個簡單的購物車。
問題:
當購物車為空時,程序將產品添加到購物車時(根據需要)使用itemid
和qty
變量創建一個新產品。 添加其他新產品時,其功能也相同。
如果再次添加(如果需要),它還能夠更新產品數量。
但是這里的問題是,它永遠找不到我添加的第一個產品,因此,每當我再次添加該產品時,它每次都會堆疊該產品,並且不會更新該產品的數量。 而對於除1st以外的其他產品,它按預期方式工作。
例如。 當產物A添加到空推車,它增加itemid
為A和qty = 1。當產物A 再次添加到空推車,它添加itemid
為A和qty=1
再次 (不做數量= 2) 。 如果我反復添加B,C或其他,它將根據需要更新其qty
<?php
public function addinTable($id){
$this->loadModel('Carts');
/////////inserting into the cart table//////////7
$item = $this->Products->get($id);
$session = $this->request->session();
$allProducts = $session->read('Cart');
if(null!=$allProducts){
echo "<br>if(allProducts is NOT EMPTY)<br>";
if(array_search($id,array_column($allProducts, 'itemid'))){
//if the id is already in list
echo "<br><b>ITEM Is IN the list already</b>";
$key = array_search($id,array_column($allProducts, 'itemid'));
echo "<br> key is ", $key;
$newqty = debug($allProducts[$key]['qty']);
echo "<br> new qty +1 = ".$newqty+=1;
debug($allProducts[$key]['qty']++);
$session->write('Cart',$allProducts);
debug( $session->read('Cart'));
}
else{
echo"<br><b>The id is not found but cart is not empty</b>";
$allProducts[] = array('itemid'=>$id,
'qty' => 1
);
debug( $session->read('Cart'));
}
}
else{///////////if cart is empty at first
echo"<br><b>The cart is empty</b>";
$allProducts[] = array('itemid'=>$id,'qty' => 1);
debug($allProducts[0]);
debug($allProducts);
debug($allProducts[0]['itemid']);
// if(array_search($id,array_column($allProducts, 'itemid'))==true){echo "hello";}
$session->write('Cart',$allProducts);
debug($session->read('Cart'));
}
$session->write('Cart',$allProducts);//save the item
}
?>
array_search()返回索引,第一個乘積為0。 0評估為false。
您需要在此處與false進行比較。
更改
if(array_search($id,array_column($allProducts, 'itemid'))) { //...
至
if(array_search($id,array_column($allProducts, 'itemid')) !== false) { //...
這是一個證明這種變化的小提琴: https : //3v4l.org/m62Ya
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.