【问题标题】:PHP For Loop doesn't iteratePHP For Loop 不迭代
【发布时间】:2016-09-08 06:23:43
【问题描述】:

我目前正在大学学习 PHP。我正在尝试创建一个功能来检查一个项目是否已经在购物车会话中。如果是,则将数量增加 1,如果不是,则将其添加到购物车数组中。

添加新项目似乎可以正常工作,并且在添加多个相同项目时该功能可以正常工作,但是,当我向数组中添加另一个项目时,问题就出在了。它添加了新项目,但是如果我尝试放置另一个相同的项目,它会将另一个项目添加到数组中,而不是将数量增加 1。

似乎 for 循环无法按我的意愿工作。任何建议将不胜感激!

    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 输出

array(3) { [0]=> array(4) { ["item_id"]=> int(1) ["item_name"]=> string(10) "粉色衬衫" ["item_price"]= > string(4) "9.99" ["item_quantity"]=> int(3) } [1]=> array(1) { [1]=> array(4) { ["item_id"]=> int(2 ) ["item_name"]=> string(14) "绿色 w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } [2]=>数组(1) { [2]=> 数组(4) { ["item_id"]=> int(2) ["item_name"]=> string(14) "Green w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } }

这是一件接一件地添加三件粉红色的衬衫,然后是两件绿色的衬衫。出于某种原因,绿色的被视为不同的项目。

对不起,如果格式不好,不确定我应该如何格式化 var_dump 现在会检查这个...

【问题讨论】:

  • 请 var_dump $_SESSION['cart'] 以便我们看到结构?
  • 添加了 $_SESSION['cart'] 的 var_dump
  • 访问这个数组似乎一切正常...尝试在 if 语句之前回显 $_SESSION['cart'][$i]["item_id"]$pID 的值,也许它会给你一个线索?

标签: php arrays for-loop


【解决方案1】:

不应该吗:

 $_SESSION['cart'][$i][$pID]["item_quantity"] += 1;

【讨论】:

  • 这似乎不是问题,似乎是循环没有检查我认为的第二个数组元素......
【解决方案2】:

好吧,我终于意识到我做错了什么。当我将另一个项目推入数组时,请参见下文:

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

应该是:

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

所以它为数组创建了另一个维度,这弄乱了我的 for 循环。如果这有任何意义,正如我所说,我仍在学习 php,并且不确定术语可以更好地解释它。

非常感谢大家的建议。使用 Marius 建议的一些调试技术帮助我发现了这个错误。

【讨论】:

    【解决方案3】:

    === 不应用于比较值。试试==

    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>";
        }
    

    http://www.w3schools.com/php/php_operators.asp

    编辑:

    如果不知道$_SESSION['cart'] 的结构,很难说还有什么问题

    【讨论】:

    • 感谢您的信息,我最初使用 == 并在看到其他人使用它后尝试了 ===。不幸的是,对结果没有影响......
    • $_SESSION['cart'][$i]["item_id"]$pID 的值是多少?尝试回应它们,你会明白为什么你的 if 语句失败了?
    • 总的来说我喜欢identical operator,因为它的明确性更可靠,​​所以你也可以考虑转换$_SESSION值。
    • 其实大部分时候你应该使用===。不同之处在于,当使用 === 时,字符串“3”将不等于数字 3。但是使用 "3" == 3 将是相等的。
    • 我不同意马吕斯的观点。除非您明确希望将 0、0.0、false、null 和 "" 视为等价,否则应使用类型和值等价运算符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多