您当前的代码将不起作用,因为所有复选框都具有相同的名称。这意味着页面上最后一个被选中的复选框将始终是表单发送的唯一值,因为它将被覆盖。
有一个解决方案! 通过在变量名称中添加方括号 ([]),您是在告诉表单将值作为数组发送,以便所有选中的选项都与表格。
如果您查看下面的代码,我在“名称”属性中添加了方括号。您可以找到有关将表单元素标记为数组的更多信息on this StackOverflow post
<td>
Ahri
<input type="checkbox" name="champ[]" value="Ahri">
</td>
<td>
Aatrox
<input type="checkbox" name="champ[]" value="Aatrox">
</td>
现在,您可以使用shuffle() 随机化数组,这样您就可以使用array_pop() 从数组中取出第一个元素,此时它将是基于已选中的复选框的随机值已选中。
当一个复选框未被选中时,它的值不会传递给表单,因此这允许您在仅选中的复选框之间随机选择。
if(isset($_POST['champ'])) {
/*I assign the array to a regular PHP variable as it's considered
bad practice to alter GLOBAL variables. If no choices are selected,
you will always get the value of "No Options Selected" because of the ternary.*/
$champ = !empty($_POST['champ'])? $_POST['champ'] : ["No Options Selected"];
/*shuffle the array, randomizing the location of each value*/
shuffle($champ);
/*array pop takes the first element off the array, and returns the value.
So we set $randomValue to the first element in the array basically.*/
$randomValue = array_pop($champ);
/*You could also overwrite the array if you want to use
the $champ variable.*/
//$champ = array_pop($champ);
/*alternatively, you could do `$randomValue = $champ[0]` for the same result,
except the array will not lose the first element.*/
//$randomValue = $champ[0];
/*You could also overwrite the array if you want to use
the $champ variable.*/
//$champ = $champ[0];
}
$randomValue 现在将包含一个基于选中复选框的随机值。
echo "Vyvolávači ".$name," pickni si ".$randomValue," na ".$line;
-本节更新:
我更改了$champ 的变量分配,以使用ternary 检查$_POST['champ'] 复选框是否为empty()。这使得如果表单页面中没有选中任何复选框,它会替换另一个数组,该数组只包含一个元素,上面写着“未选择选项”,如果没有选择任何选项,这将始终是返回。
你正在使用 PHP,你为什么不使用它?
附带说明,您可以通过使用带有可能值的循环来摆脱大量 HTML。这可以防止很多拼写错误和语法问题,并允许您更轻松地控制用户必须从中选择的选项,因为您可以轻松地基于数据库构建数组或手动构建数组以确保所有代码都是正确的每个复选框都一样。
$possibleValues = [
"Ahri",
"Aatrox",
"xx1",
"xx2",
];
foreach($possibleValues as $value) {
echo "<td>{$value}<input type='checkbox' name='champ[]' value='{$value}'/></td>";
}
旁注#2
一些合理的代码缩进是个好主意。
它可以帮助我们阅读代码,更重要的是它可以帮助您调试代码。
Take a quick look at a coding standard 为您自己的利益。
您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
正如您在我上面提供的代码中看到的(在 HTML 和 PHP 中),每一行都有特定数量的间距,使代码更具可读性。将具有多个子元素的元素分成多行(大多数情况下)也是有益的,这使得它更具可读性和更易于使用。