I'm building a website that will randomly display a yelp listing each time the page is refreshed. The yelp search api returns 20 listings in an array. Right now, I am using PHP's function rand(0,19) to generate a random listing every time the page is refreshed ( $businesses[rand(0,19)] ).
Can someone refer me to a smarter method to randomize? I want to show all 20 listings once before any of them are repeated. What is the preferred method to handle this problem?
the below answer doesn't work because the numbers are recreated every time I refresh the page. I'm guessing I need to store which 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/>";
?>
Select random rows in Excel without duplicates Only works in Excel 365 and Excel 2021 that support dynamic arrays. To select random rows with no repeats, build a formula in this way: INDEX(SORTBY(data, RANDARRAY(ROWS(data))), SEQUENCE(n), {1,2,…}) Where n is the sample size and {1,2,…} are column numbers to extract.
In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.
Use the randint() function(Returns a random number within the specified range) of the random module, to generate a random number in the range in specified range i.e, from 1 to 100.
The numbers generated are not truly random; typically, they form a sequence that repeats periodically, with a period so large that you can ignore it for ordinary purposes. The random number generator works by remembering a seed value which it uses to compute the next random number and also to compute a new seed.
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 all the listings in an array called $businesses
.
When this is completed, you will have displayed all the 20 listings at once.
Hope this helps!
try this code
$a = range(1,36);
shuffle($a);
$array = array_slice($a, 0, 3);
print_r($array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With