0

我已经结合嵌入式循环创建了一个二维数组来创建一个复选框表,如何在用户单击提交按钮后保持复选框处于选中状态?我怀疑会话变量是必要的,但我不确定如何在这段代码中实现它。这是一个类项目,我们应该在其中创建一个战舰游戏。课堂上没有人能够帮助我解决这个问题。请记住,这是一个介绍性课程,所以当您提交答案时不要指望我知道很多。这是创建板的一些代码。如果您需要更多,请告诉我。

function createBoard(){
    //building the arrays
$column1 = array(
'a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'
);
$column2 = array(
'b1','b2','b3','b4','b5','b6','b7','b8','b9','b10'
);
$column3 = array(
'c1','c2','c3','c4','c5','c6','c7','c8','c9','c10'
);
$column4 = array(
'd1','d2','d3','d4','d5','d6','d7','d8','d9','d10'
);
$column5 = array(
'e1','e2','e3','e4','e5','e6','e7','e8','e9','e10'
);
$column6 = array(
'f1','f2','f3','f4','f5','f6','f7','f8','f9','f10'
);
$column7 = array(
'g1','g2','g3','g4','g5','g6','g7','g8','g9','g10'
);
$column8 = array(
'h1','h2','h3','h4','h5','h6','h7','h8','h9','h10'
);
$column9 = array(
'i1','i2','i3','i4','i5','i6','i7','i8','i9','i10'
);
$column10 = array(
'j1','j2','j3','j4','j5','j6','j7','j8','j9','j10'
);
//build the master array
$row = array(
"a"=>$column1,
"b"=>$column2,
"c"=>$column3,
"d"=>$column4,
"e"=>$column5,
"f"=>$column6,
"g"=>$column7,
"h"=>$column8,
"i"=>$column9,
"j"=>$column10
);
    print<<<HERE
    <form method = "post"
        action = "">
    <table border = "1">

    HERE;
    for ($i="a";$i<="j";$i++){
    print "<tr>";
    foreach ($row["$i"] as $chkRow){

    print "<td><input type = 'checkbox' name = '$chkRow' value = '$chkRow'/>$chkRow</td>\n";
    }//end foreach
    print"</tr>\n";
    } //end for loop

    print "</table>";
    print "<button type = 'submit'>Fire!</button></form>";

    } //end function
4

1 回答 1

1

未经测试,在我的脑海中,但应该是构建复选框网格并在网格中添加/删除更多内容时检查它们的基础。

<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['shots'] = $_POST['shots'];
}

echo '<form method="post"><table>';
for($i = 1; $i < 10; $i++) {
   echo '<tr>';
   for ($j = 'a'; $j <= 'j'; $j++) {  // this works, but you shouldn't not be doing "math" on characters
      $has_shot = isset($_SESSION['shots'][$i][$j]) ? ' checked="checked"' : '';
      echo "<td><input type='checkbox' name='shots[$i][$j]'$has_shot /></td>";
   }
   echo '</tr>'
}
echo '</table><input type="submit"></form>';
于 2013-07-12T22:05:34.963 回答