Kurt Görg Kurt Görg - 26 days ago 20
PHP Question

How to assign values to a 2D array in a loop?

I have a 1D array of options and a 1D array of answers, 3 options and 1 answer for each question. I want to be able to randomize the positions of each row of

$randomOption
, so that's why I am trying to put it in a 2D array. I'm not sure how to do this though.

$randomOption = array();

For($x = 0; $x=$noQuestions-1; $x++){
$randomOption[$x,$x*4] = $options[$x*3];
$randomOption[$x,$x*4+1] = $options[$x*3+1];
$randomOption[$x,$x*4+2] = $options[$x*3+2];
$randomOption[$x,$x*4+3] = $answer[$x];

echo $randomOption[$x, $x*4];
echo $randomOption[$x, $x*4+1];
echo $randomOption[$x, $x*4+2];
echo $randomOption[$x, $x*4+3];
}

Answer

Man, i dont know what kind of code you have written there but I got your idea, what you want to do. Here is a working code:

// I assume you have some array with questions,their options and answers in it like : array(question, option_array, answer)
$question_option_answer_array = array(array('question1',array('a','b','c'),'a'), array('question2',array('A','B','C'),'B'), array('question3',array('I','II','III'),'I'));
$noQuestions = count($question_option_answer_array);
$options = array();
$answers = array();
for($i=0;$i<$noQuestions;$i++){
  $options[] = $question_option_answer_array[0][1];
  $answers[] = $question_option_answer_array[0][2];
}
$options = array(array('a','b','c'),array('A','B','C'),array('I','II','III'));
$answers = array('a','B','I');
$limit = count($answers);
$mixArray = array();
for($i=0;$i<$limit;$i++){
  shuffle($options[$i]);
  echo 'My Options :<br>';
  foreach($options[$i] as $op){
    echo $op.'<br>';
  }
  echo 'My answer :'.$answers[$i].'<br><br>';
}

One example output:

My Options :
c
a
b
My answer :a

My Options :
A
C
B
My answer :B

My Options :
III
II
I
My answer :I

It will change every time as you want. It organizes your options randomly every time and your answer remain intact relative to every set of option as its in different array. Use $options array to give your options and $answers array to store your answer respectively.

I hope it helps

Comments