如果表单答案与php中的数组中的答案匹配,如何显示该答案



我一直在尝试学习php,为了练习,我根据姓氏制作了一组Family Guy字符。然后我试着在表单中问一个问题,我希望代码检查数组,看看它是否与数组中的正确答案匹配。我对PHP还很陌生,这真的只是一次学习经历。代码如下。。。

<?php
$families = array(
"Griffin" => array(
"Peter",
"Louis",
"Chris",
"Stewie",
"Meg"
),
"Quagmire" => array(
"Glen"
),
"Brown" => array(
"Cleveland",
"Loretta",
"Junior"
)
);
?>
<html>
<head>
</head>
<body>
Which of these Family Guy Characters is part of the Griffin family?
<form action = "familyguyquestions.php" method = 'post'>
A: <input type = "radio" name = "cleveland">Cleveland
B: <input type = "radio" name = "glenn">Glenn
C: <input type = "radio" name = "meg">Meg
D: <input type = "radio" name = "quagmire">Quagmire
<input type = "submit" name = "submitQuestion">
</form>
</body>
</html>

有两种方法:

  • 将表单发送到php,检查答案并呈现一个页面,显示答案是否正确
  • 向服务器发出AJAX请求,并返回一个包含答案是否正确的JSON,并更新DOM

至于如何发送数据,您的单选按钮上应该有相同的name属性,并有一个隐藏的输入,以了解要查看的数组以及数组键(因为您有一个数组数组)。

html:

<html>
<head>
</head>
<body>
Which of these Family Guy Characters is part of the Griffin family?
<form action = "familyguyquestions.php" method = 'post'>
<input type="hidden" value="families" name="what_array" />
<input type="hidden" value="Griffin" name="what_array_key" />
A: <input type = "radio" name="answer" value = "cleveland">Cleveland
B: <input type = "radio" name="answer" value = "glenn">Glenn
C: <input type = "radio" name="answer" value = "meg">Meg
D: <input type = "radio" name="answer" value = "quagmire">Quagmire
<input type = "submit" name = "submitQuestion">
</form>
</body>
</html>

php:

if (false == isset($_POST['what_array'])) {
    // No array here, return an error
}
if (false == isset($_POST['what_array_key'])) {
    // No key here, return an error
}
if (false == isset($_POST['answer'])) {
    // No answer, return error
}
$the_array = $_POST['what_array'];
$the_array_key = $_POST['what_array_key'];
$the_answer = $_POST['answer'];
$the_array = ($$the_array);
if (false == isset($the_array)) {
    // Another array to look into was set, return error
}
if (true == in_array($the_answer, $the_array[$the_array_key])) {
    // Here the answer is ok
} else {
    // Wrong answer
}

注意$$the_array上的双美元符号。这就是通过字符串获取变量的方法。如果$the_array是"族",则$$the_array将是要查找的实际数组。

示例

您可以使用in_array函数进行检查,如下所示:

if (in_array($_POST['answer'], $families['Griffin'])) 
{
 // true 
}   else
{
// false
}

此外,您需要为您的单选按钮设置正确的名称,即:

A: <input type = "radio" name = "answer" value="Cleveland">Cleveland
B: <input type = "radio" name = "answer" value="Glenn">Glenn
C: <input type = "radio" name = "answer" value="Meg">Meg
D: <input type = "radio" name = "answer" value="Quagmire">Quagmire

您的单选按钮结构不正确。它们都应该具有相同的name,例如name="guess",并且每个字符名称都应该在值中,例如value="cleveland"

然后这是一个简单的事情:

if (isset($families['Griffn'][$_POST['guess']]) {
   ... correct ...
} else {
   ... wrong ...
}

但请注意,PHP数组键是CASE-SENSITIVE。表单中的名称必须与数组中的名称完全相同:

<input type="radio" name="guess" value="Cleveland"> This is correct
<input type="radio" name="guess" value="cleveland"> Incorrect, lower case c on the name.

最新更新