Jump to content

shuffle an array


Go to solution Solved by requinix,

Recommended Posts

I can't figure out why my shuffle function is behaving the way it is. I've populated a multi-dimensional array $_SESSION['data']['question'][$count], $_SESSION['data']['answer'][$count], and $_SESSION['data']['type'][$count]. When I run the code without the shuffle function, it works properly by printing the question, answer and type data to the screen. But when I use the shuffle() function, my printout to the screen is blank. Thanks. Here is my code:

 

 

 

// Get and Assign Questions and Answers
$counter = 0;
$query3 = "SELECT * FROM inno_quiz_questions WHERE quiz_id = '".$row2['id']."' ORDER BY id";
$result3= mysql_query($query3) or die("Could not perform query: ".mysql_error());
$qnum = mysql_num_rows($result3);
while ($row3 = mysql_fetch_array($result3)){
   $_SESSION['data']['question'][$counter] = $row3['question'];
   $_SESSION['data']['answer'][$counter] = $row3['answer'];
   $_SESSION['data']['type'][$counter] = $row3['type'];
   $counter++;
}
 
shuffle($_SESSION['data']); // Shuffle array
 
$count = 0;
while ($count < $_SESSION['quiz']['assigned']){
   print $count.". ".$_SESSION['data']['question'][$count]."<br>";
   print $_SESSION['data']['answer'][$count]."<br>";
   print $_SESSION['data']['type'][$count]."<br><br>";
   $count++;
}
 
Link to comment
https://forums.phpfreaks.com/topic/285529-shuffle-an-array/
Share on other sites

  • Solution

You're shuffling the arrays in $_SESSION['data']. That is, you're shuffling "question" and "answer" and "type" around amongst themselves. You aren't actually shuffling the questions, answers, or types.

 

You need to put each question+answer+type tuple into an array and put that array into the session as a unit. Then you can shuffle it.

while ($row3 = mysql_fetch_array($result3)) {
    $_SESSION['data'][] = $row3; // as the key/values are identical
}
print $count . ". " . $_SESSION['data'][$count]['question'] . "<br>";
print $_SESSION['data'][$count]['answer'];
print $_SESSION['data'][$count]['type'];
Link to comment
https://forums.phpfreaks.com/topic/285529-shuffle-an-array/#findComment-1465892
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.