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


How to generate random radio button positions?

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

这里有四个单选按钮,每个问题都有四个答案。问题是每个问题都应该有随机答案选项
正确答案将包含值=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并从数据库中获取选项值。

使用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

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

注:Didnt测试