循环数组,一个按钮中有2个字段

looping arrays, 2 fields in one button

本文关键字:按钮 2个 字段 一个 数组 循环      更新时间:2023-09-26

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

这就是购物车,我把我的物品放在一个会话变量(数组)中。在我的购物车页面中,我每行有2个表单(编辑数量和删除项目)。我想做的是把所有的按钮变成一个。

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

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

我尝试(其中之一)将cartOutput循环变成一个表单,有一个提交按钮。。。则对于每个字段将是一个数组。我认为可以这样做,但我做不到,我把我的字段改为"quantity[]"answers"item_to_adjust[]"以进行数组输入,我编辑了我的php操作,添加了另一个用于循环的操作

这是我的代码:

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
}

会话结构

将您的项目存储在由项目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>';

将商品添加到购物车

提交表格后,您可以循环浏览通过邮寄收到的数量数组,并更新您的会话数据

// 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并提交表单。