将插入的字段数与动态插入的文本框进行匹配

时间:2013-11-23 05:45:48

标签: php session

book.php

<input type="text" id="total_seats" name="total_seats" value="" readonly /></td>

view.php

<?php
   $serial_no = 1;
$seats = explode(',', $_SESSION['total_seats']);
foreach ($seats as $seat) { ?>
<tr>
    <td> <?php echo $serial_no++; ?></td>
      <td><?php echo $seat; ?> </td>
           <td><input type="text" name="passenger_name[]" style="border:1px solid #000;" required /></td>

        </tr>

在book.php页面中,total_seats包含通过复选框插入的座位数,此代码运行完全正常,但是当我检查3个复选框&amp; total_seats包含3个座位号码,它在我的view.php页面中显示4个文本字段以及序列号最多4个。如何将我的座位号码与输入的total_seats匹配,而没有一个额外的字段..

提前致谢。

2 个答案:

答案 0 :(得分:0)

检查这种情况是否发生在你的情况下(在字符串的末尾还有一个',',所以你最后还有一个空元素:

$seats = explode(".", "a,b,c,d,");

print_r($seats);

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => 
)

编辑:针对此案例使用解决方案进行更新 - 使用rtrim()删除最后一个逗号

$total_seats = $_SESSION['total_seats'];
$seats = explode(',', rtrim($total_seats, ",")); // cut trailing commas
foreach ($seats as $seat){
  .. below are the same

答案 1 :(得分:0)

我90%确定您的问题是total_seats contains the number of seats inserted through checkboxes,其余代码应该按原样运行。我认为您正在做的是为您检查的每个复选框的total_seats值添加#,。爆炸时,如果您有四个值和4个逗号,例如"1,2,3,4,",那么您将有五个值:

array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(0) ""
}

请确保不要在最后一个席位#

后面加上最后一个逗号