mysql - array shuffle with key for quiz php
Get the solution ↓↓↓<?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>
In my MySQL table, I have stored;
id question answer1 answer2 answer3 answer4 ans_key date
1 1+1= 2 3 1 6 1 2014-08-03
here is ans_key;
1 =answer1
2 =answer2
3 =answer3
4 =answer4
I am using Ajax to send user's answer.
I want to check the answer key with the relevant value, after array shuffle, how to get the key value to check if the answer is right or not?
Answer
Solution:
i found the answer
<?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
}
?>
here data-key holds the key value of array
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: npm err! code 1
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.