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个复选框&total_seats包含3个座位号,在我的view.php页面中显示了4个文本字段和最多4个序列号。。如果没有一个额外的字段,我如何将我的座位号与我输入的total_seats相匹配。。
提前谢谢。
检查这种情况是否发生在您的案例中(字符串末尾还有一个","),因此您在末尾有一个额外的空元素:
$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
我90%确信您的问题在于total_seats contains the number of seats inserted through checkboxes
,其余代码应该按原样运行。我认为您正在做的是将#,
添加到选中的每个复选框的total_seats值中。使用爆炸,如果您有四个值和四个逗号(如"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) ""
}
请确保不要在最后一个座位#后面包含最后一个逗号