数组shuffle with key for quiz php

s4n0splo  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(112)
<?php
$qq=mysql_query("select * from quiz");
$row=mysql_fetch_array($qq);
//var_dump($row);
    $question = $row['question'];
    $_SESSION['quiz_id']=$row['id'];
    $ans_array = array($row['answer1'],$row['answer2'],$row['answer3'],$row['answer4']);
    shuffle($ans_array);
?>
<form name="qform" id="qform">
 <h2> <?php echo $question; ?></h2>   
 <label><input type="radio" value="<?php echo $ans_array[0]; ?>" name="answer"> <?php echo $ans_array[0]; ?></label>
 <label><input type="radio" value="<?php echo $ans_array[1]; ?>" name="answer"> <?php echo $ans_array[1]; ?></label>
 <label><input type="radio" value="<?php echo $ans_array[2]; ?>" name="answer"> <?php echo $ans_array[2]; ?></label>
 <label><input type="radio" value="<?php echo $ans_array[3]; ?>" name="answer"> <?php echo $ans_array[3]; ?></label>
    <p id="submit-row-btn"><input type="submit" id="quiz_submit" class="q_submit" value="Submit">
    <input type="submit" id="quiz_ans_submit" value="Check Answer" class="q_submit" style="display:none">
    <span id="ans_err"></span></p>
 </form>

在我的MySQL表中,我已经存储了;

id   question   answer1     answer2     answer3     answer4     ans_key     date
1     1+1=        2           3           1           6           1     2014-08-03

这里是 ans_key;
我使用 AJAX 发送用户的答案。
我想检查答案键与相关值,数组 Shuffle 后,如何得到键值来检查答案是否正确?

waxmsbnn

waxmsbnn1#

我找到了答案

<?php
$ans_array = array(1=>$row['answer1'],$row['answer2'],$row['answer3'],$row['answer4']);
$shuffleKeys = array_keys($ans_array);
shuffle($shuffleKeys);
$newArray = array();
    foreach($shuffleKeys as $key) 
    {
        $newArray[$key] = $ans_array[$key];
    ?>
        <label><input type="radio" value="<?php echo $newArray[$key] ?>" data-key="<?php echo $key;?>" name="answer"> <?php echo $newArray[$key]; ?></label>
    <?php
    }
    ?>

这里data-key保存数组的键值

ijxebb2r

ijxebb2r2#

$generate_array = array();
for( $i=1; $i<=50; $i++ )
{
    array_push($generate_array,$i);
}
print_r($this->array_shuffle($generate_array));
function array_shuffle($array){
$i = count($array);
while(--$i){
$j = mt_rand(0,$i);
if($i != $j){
$tmp = $array[$j];
$array[$j] = $array[$i];
$array[$i] = $tmp;
}
}   
return $array;
}

相关问题