【问题标题】:looping arrays, 2 fields in one button循环数组,一键2个字段
【发布时间】:2014-10-23 19:39:56
【问题描述】:

我搜索了一些答案并找到了一个,但并没有真正说出代码,而是很好的逻辑。但我还没有做对,我尝试了很多次。

所以这是购物车,我将我的商品放入会话变量(数组)中。在我的购物车页面中,我每行有 2 个表单(编辑数量和删除项目)。我想要做的是将整体按钮合二为一。

因此,当更改任何数量字段(或选中“删除项目”框)时,如果我单击那个提交按钮,它将更新全部而不是每次操作的一个表单。

***所以这是我的原始代码:(***已编辑,请参阅帖子的最后 3 种形式)

我尝试(其中之一)做的是将 cartOutput 循环变成一种形式,只有一个提交按钮......然后每个字段都是一个数组。我认为可以这样做,但我做不到,我将我的字段更改为 'quantity[]' 和 'item_to_adjust[]' 有一个数组输入,我编辑了我的 php 操作,添加了另一个 for 循环

这是我的代码:

foreach ($_SESSION["cart_array"] as $each_item) { 
          $i++;
          while (list($key, $value) = each($each_item)) {
                  if ($key == "item_id" && $value == $item_to_adjust) {
                      foreach($cart_items_new as $item_id => $quantity) {
                      // That item is in cart already so let's adjust its quantity using array_splice()
                      array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                      }
                  } // close if condition
          } // close while loop
} // close foreach loop

是的,它不起作用,它提交但什么也没做,请原谅我的混乱。

编辑: (当用户添加新的购物车商品时)

if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) { 
    // RUN IF THE CART IS EMPTY OR NOT SET
    $_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
} else {
    // RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
    foreach ($_SESSION["cart_array"] as $each_item) { 
          $i++;
          while (list($key, $value) = each($each_item)) {
              if ($key == "item_id" && $value == $pid) {
                  // That item is in cart already so let's adjust its quantity using array_splice()
                  array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
                  $wasFound = true;
              } // close if condition
          } // close while loop
       } // close foreach loop
       if ($wasFound == false) {
           array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
       }
}
header("location: cart.php"); 
exit();
}

(查看和渲染购物车,我将只包括编辑和删除部分)

if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h2 align='center'><font face='Verdana'>Your shopping cart is empty</font></h2><br>";
} else {
    foreach ($_SESSION["cart_array"] as $each_item) { 
        $item_id = $each_item['item_id'];
        $sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
        while ($row = mysql_fetch_array($sql)) {
            $product_name = $row["product_name"];
            $price = $row["price"];
            $details = $row["details"];
            $quantity = $row['quantity'];
        }

//EDIT
$cartOutput .= '<td><form action="cart.php" method="post">
    <input name="quantity" id="price" type="text" value="' . $each_item['quantity'] . '" class="form-control input-xsmall gitna"  maxlength="1" />
    <center><input name="adjustBtn' . $item_id . '" type="submit" value="change"  class="btn btn-primary"/></center>
    <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
    </form></td>';

//DELETE
    $cartOutput .= '<td><form action="cart.php" method="post"><center>
<input name="deleteBtn' . $item_id . '" class="btn btn-danger" type="submit" value="X" 
/></center><input name="index_to_remove" type="hidden" value="' . $i . '" /></form>
</td>';

然后在提交之后,会发生以下情况:

        if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
    // execute some code
    $item_to_adjust = $_POST['item_to_adjust'];
    $quantity = $_POST['quantity'];
    $quantity = preg_replace('#[^0-9]#i', '', $quantity); // filter everything but numbers
    if ($quantity >= 100) { $quantity = 99; }
    if ($quantity < 1) { $quantity = 1; }
    if ($quantity == "") { $quantity = 1; }
    $i = 0;
    foreach ($_SESSION["cart_array"] as $each_item) { 
              $i++;
              while (list($key, $value) = each($each_item)) {
                  if ($key == "item_id" && $value == $item_to_adjust) {
                      // That item is in cart already so let's adjust its quantity using array_splice()
                      array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
                  } // close if condition
              } // close while loop
    } // close foreach loop
}

【问题讨论】:

  • 只是一个想法:制作一个新的提交表单。使用 jQuery 捕获表单提交并阻止它执行任何操作(preventDefault)。接下来让函数使用 .submit() 提交所有其他表单

标签: javascript php jquery arrays forms


【解决方案1】:

会话结构

将您的项目存储在由项目 ID 索引的会话中。

$_SESSION['cart_array'][ $itemId ] = $quantity;

您这样保存商品,这样访问购物车中的商品就比较麻烦了

$_SESSION['cart_array'][0] [ 'item_id' ] = $itemId;
$_SESSION['cart_array'][0] [ 'quantity' ] = $quantity;

构建您的表单

使您的购物车一个形式。 以这样的方式为每个条目创建一个输入字段

print '<form action="cart.php" method="post">';
foreach ($_SESSION['cart_array'] as $itemId => $quantity) {
  // query product information from database here

  // build form row with one input field for each entry in the cart
  print '<tr>';
  print '<td> add product information here </td>'
  print '<td><input name="quantity['.$itemId.']" value="'.$quantity.'"></td>';
  print '</tr>';
}
print '</form>';

将商品添加到购物车

提交表单后,您可以遍历通过 post 收到的数量数组并更新会话数据

// check if cart already exists. if not, init it.
if (!isset(_SESSION['cart_array']) {
   $_SESSION['cart_array'] = array();
// otherwise save itemIds and their quantities
} else {
  foreach ($_POST['quantity'] as $itemId => $itemQuantity) {
    // if the given quantity is 0 remove the item from the cart
    if ($itemQuantity == 0) {
      unset($_SESSION['cart_array'][ $itemId ])
    // otherwise save or update the quantity for the given item
    } else {
      $_SESSION['cart_array'][ $itemId ] ['quantity'] = $itemQuantity; 
    }
  }
}

在表单中添加删除按钮

如果其余部分正常,您可以添加删除按钮。按钮必须通过javascript将相应输入字段的值设置为0并提交表单。

【讨论】:

  • 我无法让它工作,我还调整了名称以使其适合我的代码,但提交后没有错误但没有任何反应。请问您是否可以调整适合我的代码的名称。如果您需要,我可以发布我的代码的其他信息。
  • 您能否在提交后发布会话转储和发布数组? '; print_r($_POST); print_r($_SESSION); ?>
  • 对不起,我已经编辑了我的答案,但忘记在 cmets 中回复,谢谢。
  • 嗯,喂?有人帮忙吗?
  • 我编辑了我的答案以使我的观点更清楚。希望它能让你更容易理解这种方法。
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 2021-11-01
  • 2019-09-28
相关资源
最近更新 更多