繁体   English   中英

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

[英]Match the number of inserted field with dynamically inserted text boxes

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个座位号时,它显示4个文本字段以及序列号,最多4个view.php页面..如何将我的座位号与输入的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值中添加#, 使用explode时,如果您有四个值和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) ""
}

请确保不要在最后一个座位后加上最后一个逗号

暂无
暂无

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

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