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 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错