mardi 25 avril 2017

How to use PHP Arrays to receive random numbers with no duplicating

I can't provide the HTML due to my site not being live. Though I know from theory coding a professional will hopefully be able to follow my logic.

My Goal I want to use PHP to create the following:

  1. Place 00 to 99 into an array.
  2. Retrieve a random number from the array.
  3. Store/Use the retrieved random from the array to place in a mysql_query as seen with number = $question Note here (Do I really require ORDER BY RAND() here?)
  4. Remove the selected random number from the array list of numbers
  5. Fetch and display the random number
  6. Once all numbers have been used then an error displays saying, refresh page to reset numbers.

The next time I want another random number it cannot duplicate the same random number it selected from the array before. So if I used the code above say 109 times then only 1 number is left in the array.

Code:

//Place all question numbers into an array

$array = [0,1,2,3,4,5,6,7,8,9,00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99]; 

//pick a random point from the array

$random = mt_rand(0,count($array)-1);

//store the random question number

$question = $array[$random];

// Select information from database and use array to assign to the selected row.

$query = mysql_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE number = $question ORDER BY RAND() LIMIT 1");

// Remove random number that was chosen from the array, so the next time the random number is ran, it won't be found in the array.

unset($array[$random]);

//fetch result to print on page

$arrayss = mysql_fetch_row($query);

//Echo result as json
echo json_encode($arrayss);

I hope this makes sense, I'm having a difficult time find out how to do it, I have searched for hours and can't get my head around it. :)




Aucun commentaire:

Enregistrer un commentaire