生成不重复的随机数 [英] Generating random numbers without repeats

查看:40
本文介绍了生成不重复的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个网站,每次刷新页面时都会随机显示一个 yelp 列表.yelp 搜索 API 以数组形式返回 20 个列表.现在,我正在使用 PHP 的函数 rand(0,19) 在每次刷新页面时生成一个随机列表 ( $businesses[rand(0,19)] ).

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)] ).

有人可以给我推荐一种更聪明的随机方法吗?我想在重复之前显示所有 20 个列表一次.处理此问题的首选方法是什么?

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/>";

?>

推荐答案

最简单的解决方案:

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

替代方案:

<?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

?>

类似问题:#5612656

键盘:http://codepad.org/cBaGHxFU

更新:

您将获得名为 $businesses 的数组中的所有列表.

You're getting all the listings in an array called $businesses.

  1. 使用上面给出的方法生成一个随机列表 ID,然后将其存储在您的数据库表中.
  2. 在每次刷新页面时,生成一个随机列表 ID,并检查它是否与数据库中的值匹配.如果没有,请显示该列表并将该值添加到您的表格中.
  3. 转到第 1 步.

完成后,您将一次显示所有 20 个列表.

When this is completed, you will have displayed all the 20 listings at once.

希望这会有所帮助!

这篇关于生成不重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆