如何将checbox数组与PHP形式的数量数组相关联

  • 本文关键字:数组 关联 PHP checbox php arrays
  • 更新时间 :
  • 英文 :


提交后,我有一个与所选数量[]关联的box[]复选框表单,如果我没有选中第一个复选框,我将无法获得复选框对应的数量。

这是我的代码

<input class="form-check-input" name="box[0]" type="checkbox" value="DVD Shipper" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">DVD Shipper</label>
</div>
<div class="invalid-feedback">Choose at least one box</div>
</div>
<div class="divTableCell">
<select class="form-select" name="quantity[]">
<option value="">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="invalid-feedback">The quantity is required!</div>
</div>
</div>
<div class="divTableRow">
<div class="divTableCell">
<div class="form-check">

<input class="form-check-input" name="box[1]" type="checkbox" value="Small Security" id="flexCheckDefault">
<label class="form-check-label" for="flexCheckDefault">Small Security</label>
</div>
<div class="invalid-feedback">Choose at least one box</div>
</div>
<div class="divTableCell">
<select class="form-select" name="quantity[]">
<option value="">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="invalid-feedback">The quantity is required!</div>
</div>
</div>

PHP代码:

if(isset($_POST['submit'])){
$ct=0;
$stationName=$_POST['stationname'];
foreach( $_POST['box'] as $k=> $value ){ // loop through array
$station = $stationName;
$box_name = addslashes( $value );  // set name based on value
$quantity     = addslashes($_POST['quantity'][$ct] ); // set qty using $ct to identify # out of total submitted
$db->query("INSERT INTO products (station, box, quantity) VALUES('".$station."', '".$box."', '".$quantity."')");
$ct++; // increment +1
}
}

如果没有很好地解释我的问题,我很抱歉,只是想让你知道英语不是我的第一语言。

我想我已经找到了如何处理这个问题,下面是代码

if (isset($_POST['add'])) {
if(!empty($_POST['box'])){
$quantityArray = array_filter($_POST['quantity'],"quantityFilter");
$stationName = $_POST['stationname'];
$inserted= false;
foreach($_POST['box'] as $boxes => $values ){ // loop through array
$k = (int)$boxes;
$station = $stationName;
$box  = addslashes($values);  // set name based on value
$quantity = addslashes($quantityArray[$k] ); // set qty using $ct to identify # out of total submitted
// same as set qty

$db->insert($station, $box, $quantity);

$k++; // increment +1
$inserted = true;
}
```

最新更新