php - Generating random numbers without repeats -


i'm building website randomly display yelp listing each time page refreshed. yelp search api returns 20 listings in array. right now, using php's function rand(0,19) generate random listing every time page refreshed ( $businesses[rand(0,19)] ).

can refer me smarter method randomize? want show 20 listings once before of them repeated. preferred method handle problem?

the below answer doesn't work because numbers recreated every time refresh page. i'm guessing need store numbers i've used already?

$numbers = range(0, 19);  shuffle($numbers); 

// handle yelp response data $response = json_decode($data); $random = rand(1,19); $business = $response->businesses;  echo "<img border=0 src='".$business[$random]->image_url."'><br/>"; echo $business[$random]->name."<br/>"; echo "<img border=0 src='".$business[$random]->rating_img_url_large."'><br/>";  ?> 

easiest solution:

$numbers = range(1, 20); shuffle($numbers); 

alternative:

<?php  function randomgen($min, $max, $quantity) {     $numbers = range($min, $max);     shuffle($numbers);     return array_slice($numbers, 0, $quantity); }  print_r(randomgen(0,20,20)); //generates 20 unique random numbers  ?> 

similar question: #5612656

codepad: http://codepad.org/cbaghxfu

update:

you're getting listings in array called $businesses.

  1. generate random listing id using method given above, , store database table.
  2. on each page refresh, generate random listing id, , check if matches value in database. if not, display listing , add value table.
  3. go step 1.

when completed, have displayed 20 listings @ once.

hope helps!


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -