如何生成随机单选按钮位置?

时间:2016-03-31 03:59:56

标签: php html

我知道我的问题标题不清楚,我会在这里解释。

有四个单选按钮及其类似的检查测试,每个问题有4个答案。问题是每个问题都应该有随机答案选项。
正确的答案将包含值= 1.

Q1这是问题1?

<input type ="radio" value="1" />
<input type ="radio" value="2" />
<input type ="radio" value="3" />
<input type ="radio" value="4" />

Q2这是问题2?

 <input type ="radio" value="2" />
    <input type ="radio" value="4" />
    <input type ="radio" value="1" />
    <input type ="radio" value="3" />

如何生成随机选项?

我正在使用PHP并从数据库中获取选项值。

2 个答案:

答案 0 :(得分:3)

使用PHP,您可以创建一个包含所有可能值的数组,然后填充它们:

$vals = [1, 2, 3, 4];
shuffle ($vals);
for ($i = 0; $i < count ($vals); $i++) : ?>
    <input type="radio" value="<?php echo $vals[$i] ?>" />
<?php endfor ?>

每当您想要新的随机值时,您都可以再次致电shuffle

答案 1 :(得分:0)

select * from your_table order by rand()

E X A M P L E

<强>数据库:

TABLE: question
id question
1  what is..
2  when did..
3  Which one..

TABLE: answer
id question_id answer_options  correct
1  1           answer 1        0
2  1           answer 2        1
3  1           answer 3        0
4  1           answer 4        0

<强>查询:

Question loop STARTS

# Use the question_id to loop through the below
$query        = "SELECT * FROM answer where question_id='$question_id' order by rand()";
$qr           = mysqli_query($con, $query);
if (mysqli_num_rows($qr) > 0)
{
$count = 2;
while ($res = mysqli_fetch_object($qr))
{
    if ($res->correct == 1)
    $value = 1;
    else
    $value = $count++;

    echo '<input type="radio" value="'.$value.'" /> '.$res->answer_options;
}
}

Question loop ENDS

注意:未经测试