php 生成不重复的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17778723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating random numbers without repeats
提问by ryank
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)] ).
我正在构建一个网站,每次刷新页面时都会随机显示一个 yelp 列表。yelp 搜索 API 以数组形式返回 20 个列表。现在,我正在使用 PHP 的函数 rand(0,19) 在每次刷新页面时生成一个随机列表( $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?
有人可以向我推荐一种更聪明的随机方法吗?我想在重复之前显示所有 20 个列表一次。处理这个问题的首选方法是什么?
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/>";
?>
回答by Amal Murali
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
类似问题:#5612656
Codepad: http://codepad.org/cBaGHxFU
键盘:http: //codepad.org/cBaGHxFU
Update:
更新:
You're getting all the listings in an array called $businesses
.
您将获得一个名为 的数组中的所有列表$businesses
。
- Generate a random listing ID using the method given above, and then store it your database table.
- On each page refresh, generate a random listing ID, and check if it matches the value in your database. If not, display that listing and add that value to your table.
- Go to step 1.
- 使用上面给出的方法生成一个随机列表 ID,然后将其存储在您的数据库表中。
- 在每次页面刷新时,生成一个随机列表 ID,并检查它是否与数据库中的值匹配。如果没有,请显示该列表并将该值添加到您的表中。
- 转到步骤 1。
When this is completed, you will have displayed all the 20 listings at once.
完成后,您将一次显示所有 20 个列表。
Hope this helps!
希望这可以帮助!
回答by Gazi Anis
I would try this via while loop:
我会通过while循环尝试这个:
<?php
$i = 0;
$arr = array();
while($i<10){
$num = rand(1, 12);
$c = 0;
echo $num . "<br>";
for($j=0; $j<4; $j++){
if($arr[$j] == $num){
$c++;
break;
}
}
if($c==0){
$arr[$i] = $num;
$i++;
}
}
echo "<pre>";
print_r($arr);
echo "</pre>";