As you build a website that employs random selection to display a Yelp listing with each page refresh, you encounter the challenge of ensuring that all 20 listings are displayed once without repetition. While the current approach using rand(0,19) offers a simple solution, it doesn't prevent repeated displays.
A more efficient strategy is to shuffle an array containing numbers representing each listing. This can be achieved with PHP's shuffle() function. But to showcase unique listings across multiple page refreshes, you'll need to track the numbers already used.
Here's an improved version of your PHP code:
<code class="php">// Generate an array of numbers without repeats $numbers = range(0, 19); shuffle($numbers); // Handle Yelp response data $response = json_decode($data); $business = $response->businesses; // Iterate through the numbers array foreach ($numbers as $i) { // Display the corresponding Yelp listing echo "<img border=0 src='" . $business[$i]->image_url . "'><br/>"; echo $business[$i]->name . "<br/>"; echo "<img border=0 src='" . $business[$i]->rating_img_url_large . "'><br/>"; }</code>
In this approach, when a page is refreshed, the $numbers array is randomized once. As the program iterates through the array, it displays each listing in order, ensuring that all 20 listings are shown without repetition.
You could also explore an alternative using the randomGen() function:
<code class="php">function randomGen($min, $max, $quantity) { $numbers = range($min, $max); shuffle($numbers); return array_slice($numbers, 0, $quantity); } // Generate 20 unique random numbers within the range of 0 to 20 $uniqueNumbers = randomGen(0, 20, 20);</code>
This function provides a more versatile approach to generating unique random numbers within a specified range and quantity.
The above is the detailed content of How to Generate Random Numbers Without Repetition in PHP for webpage listing. For more information, please follow other related articles on the PHP Chinese website!