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
.
- generate random listing id using method given above, , store database table.
- on each page refresh, generate random listing id, , check if matches value in database. if not, display listing , add value table.
- go step 1.
when completed, have displayed 20 listings @ once.
hope helps!
Comments
Post a Comment