doudou3213 2016-05-12 12:13
浏览 40
已采纳

PHP For循环不迭代

I am currently learning PHP at college. I am trying to make a function to check whether or not an item is already in the cart session. If it is then increment the quantity by 1, if not, then add it the item to the cart array.

It seems to work fine adding the new item and the function works when adding multiples of the same item however, the problem lies when I add another item to the array. It adds the new item but then if I try and place another of the same item it adds another item to the array instead of increasing the quantity by 1.

It seems like the for loop doesn't work how I want it to. Any advice would be appreciated thanks!

    function addItemToCart($mysqli) {

  $itemID = (int)$_GET['add'];
  $counterItemsInCart = 0;
  $alreadyInCart = false;

  if(is_int($itemID)) { //makes sure the ID is passed as an int

    $query = "SELECT product_id, product_name, product_price FROM product WHERE product_id = ?";
    $stmt = $mysqli->prepare($query);
    $stmt->bind_param("i", $itemID); // bind variables
    $stmt->execute();
    $result = $stmt->get_result();

    if($rows = $result->fetch_assoc())
    {
      //setts all info needed to variables.
      $pID = $rows['product_id'];
      $pName = $rows['product_name'];
      $pPrice = $rows['product_price'];
    }
    else
    {
      //if the item id is not an int display this message...
      echo "not working";
    }
    if(isset($_SESSION['cart'])) { //check if any item in cart already
      $intArraySize = count($_SESSION['cart']);
      //loop through cart array
      for($i = 0; $i < $intArraySize; $i+=1)
      {
        //check if item already exists in cart.
        if($_SESSION['cart'][$i]["item_id"] === $pID)
        {
          $_SESSION['cart'][$i]["item_quantity"] += 1;
          $alreadyInCart = true;
          echo "<script type='text/javascript'>alert('item in cart');</script>";
        }
      }//loop to cycle through items in array...
      if($alreadyInCart === false) { echo "<script type='text/javascript'>alert('item not in cart');</script>";
        array_push($_SESSION['cart'], array($intArraySize =>array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1)));
      }//close if statement check if same item is in array, if not add it.
    }//close if statement checking if any item at all in shopping cart.
    else {echo "<script type='text/javascript'>alert('new item');</script>";
      $_SESSION['cart'] = array(array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1));
    }
  }//ends if statement checking if the id of the item is a int or string.
}//ends function

var_dump output

array(3) { [0]=> array(4) { ["item_id"]=> int(1) ["item_name"]=> string(10) "Pink Shirt" ["item_price"]=> string(4) "9.99" ["item_quantity"]=> int(3) } [1]=> array(1) { [1]=> array(4) { ["item_id"]=> int(2) ["item_name"]=> string(14) "Green w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } [2]=> array(1) { [2]=> array(4) { ["item_id"]=> int(2) ["item_name"]=> string(14) "Green w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } }

This was adding three pink shirts one after another and then two green. For some reason the green ones are seen as different items.

Sorry if the format is bad, not sure how I should format a var_dump will check this now...

  • 写回答

3条回答 默认 最新

  • dpfw3607 2016-05-12 13:17
    关注

    Ok I finally realised what I had done wrong. When I pushed another item in to the array see below:

    array_push($_SESSION['cart'], array($intArraySize =>array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1)));
    

    It should have been:

    array_push($_SESSION['cart'], array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1));
    

    So it was creating another dimension to the array which was messing up my for loop. If that makes any sense, as I said I am still learning php and am not sure of the terminology to explain it any better.

    Many Thanks to all for the advice. Using some of the debugging techniques Marius advised helped me see this error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同