繁体   English   中英

在php购物车中找不到数组项目

[英]Array item could not be found in php shopping cart

我在PHP数组中遇到一种奇怪的情况。 我正在尝试使用会话变量创建一个简单的购物车。

问题:

当购物车为空时,程序将产品添加到购物车时(根据需要)使用itemidqty变量创建一个新产品。 添加其他新产品时,其功能也相同。

如果再次添加(如果需要),它还能够更新产品数量。

但是这里的问题是,它永远找不到我添加的第一个产品,因此,每当我再次添加该产品时,它每次都会堆叠该产品,并且不会更新该产品的数量。 而对于除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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM