简体   繁体   English

PHP使用循环获取表数据行输入值

[英]PHP get the table data row input value using loop

I am having a issue in getting the correct value from the table . 我在从table中获取正确的值时遇到问题。

The issue I encountered: 我遇到的问题:

  • When I choose the second checkbox the and input a quantity , it is Undefined offset: 0 当我选择的第二个checkbox并输入quantity ,它是未定义的偏移量:0

But the value of the checkbox is working and correct. 但是该checkbox的值有效且正确。

What I am expecting is when I choose the second or other checkbox (exclude first checkbox ), I should get the value of that input field. 我期望的是,当我选择第二个或其他checkbox (不包括第一个checkbox )时,我应该获得该输入字段的值。

HTML 的HTML

<?php foreach($results as $row) { ?>
<tr>
    <td><input type="checkbox" name="products[]" value="<?php echo $row->items_id; ?>"></td>
    <td><?php echo $row->item_name; ?></td>
    <td><input type="number" name="quantity[]" class="form-control"></td>
</tr>
<?php } ?>
<input type="submit" name="process" class="btn btn-primary" value="Process">

PHP 的PHP

$quantity = $_POST['quantity'];
$products = $_POST['products'];
$count_selected = count($products);

for($i=0; $i< $count_selected; $i++){
    var_dump($quantity[$i]); exit;
}

视图的样本图像

The problem with checkboxes is that an unchecked one submits no value so your $_POST['products'] and $_POST['quantity'] arrays may have different lengths. 复选框的问题在于未选中的复选框未提交任何值,因此$_POST['products']$_POST['quantity']数组的长度可能不同。

I'd combine using a hidden input with specific array indexes. 我将结合使用隐藏的输入和特定的数组索引。

For example 例如

<?php foreach($results as $row) : ?>
<tr>
    <td>
        <input type="hidden" name="products[<?= $row->items_id ?>]" value="0">
        <input type="checkbox" name="products[<?= $row->items_id ?>]" value="1">
    </td>
    <td><?= htmlspecialchars($row->item_name) ?></td>
    <td><input type="number" name="quantity[<?= $row->items_id ?>]" class="form-control"></td>
</tr>
<?php endforeach ?>

Then the arrays will have the same indexes and you can iterate them with a foreach 然后,数组将具有相同的索引,您可以使用foreach对其进行迭代

foreach ($_POST['products'] as $itemId => $checked) {
    // $checked represents the state of the checkbox
    // you can access quantity via $_POST['quantity'][$itemId]
}

You could even create a nice filtered array of quantities via 您甚至可以通过以下方式创建一个很好的过滤数量数组

$selections = $_POST['products'];
$quantities = array_filter($_POST['quantity', function($itemId) use ($selections) {
    return $selections[$itemId];
}, ARRAY_FILTER_USE_KEY);

first, define array variable. 首先,定义数组变量。 $products =array( ); $ products = array(); $quantity=array( ); $ quantity = array(); other wise every thing seems fine. 其他方面,每件事似乎都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM