首页 > 解决方案 > 如果选中行,则从表列中获取值

问题描述

我正在使用 PHP 从表中获取值并需要进一步处理它们。如果选中行,我需要从 Quantity 和 FMK Code 列中获取值。

桌子:

<table class="table table-bordered">
    <thead>
        <tr class="success">
            <th>#<br/></th> 
            <th>Article  </th>
            <th>Name  </th> 
            <th>Quantity</th> 
            <th>FMK CODE<br/></th>
        </tr>
    </thead>
    <tbody>
        <?php 
            $i = 1; 
            while($r=$q->fetch()){  ?>
            <tr>
                <td><input type="checkbox" class="from-control" name="id[]" value="<?php echo $r['id']?>"></td>
                <td><?=$r['Article']?></td>  
                <td><?=$r['Name']?></td>     
                <td><input type="text" class="form-control" value="<?=$r['quantity'];?>" name="quantity"></td>   
                <td> 
                    <select class="form-control col-lg-2" name="childCode"><?php getChildCodes($r["code"]) ?></select>
                </td>
            </tr>
        <?php } ?>      
    </tbody>
</table>

在提交时,我需要从“数量和子代码”中获取所选每一行的值。

<button type="submit" name="getValues"> Submit </button>

PhP处理:

<?php 

    if (isset($_POST['getValues'])) {

        $id = $_POST['id'];
        $quantity = $_POST['quantity'];
        $childCode = $_POST['childCode'];

        $values = array(); 

        foreach($id as $id) {
            foreach($quantity as $quant){
                foreach($childCode as $code){
                    array_push($values, $id,$quant,$code);
            }
        }           
        echo "<pre>";
        var_dump($values);
        echo "</pre>";          
    }
?>

值输出。在输出中,我从表中获取所有值,无论它们是否被检查是错误的。数组打印也不好,来自一个名称的数组的值。我需要将数组形成 id、数量、子代码的第一个元素到 b 一个数组。[0]=>"177239","10.000",113

array(3) {
  [0]=>
  array(1) {
    [0]=>
    array(3) {
      [0]=>
      string(6) "177239"
      [1]=>
      string(6) "177240"
      [2]=>
      string(6) "177241"
    }
  }
  [1]=>
  array(3) {
    [0]=>
    string(6) "10.000"
    [1]=>
    string(7) "100.000"
    [2]=>
    string(6) "10.000"
  }
  [2]=>
  array(3) {
    [0]=>
    string(11) "113"
    [1]=>
    string(10) "87"
    [2]=>
    string(10) "91"
  }
}

标签: php

解决方案


misorude 指出您需要以构建 PHP 数组的样式命名表单元素。这是用[]提到的字符完成的。所以第一行会有像<input name="id[0]" ...,这样的元素名称<input name="quantity[0]" ...。第二行将具有元素名称,例如<input name="id[1]"<input name="quantity[1]"

还要确保foreach块不会覆盖$id变量:)

foreach($id as $id) // Oops!

推荐阅读