PHP中如何保证随机数唯一且不重复?

Barbara Streisand
发布: 2024-10-21 11:58:02
原创
798 人浏览过

How to Ensure Unique Random Numbers Without Repeats in PHP?

生成不重复的随机数

您当前使用 rand() 函数生成随机 Yelp 列表的方法不能确保列表的唯一性。为了防止重复,请考虑实施更智能的随机化策略。

一种方法是对代表列表索引的一系列数字使用本机 shuffle() 函数。这会生成一个没有重复项的打乱数组:

<code class="php">$numbers = range(0, 19);
shuffle($numbers);</code>
登录后复制

另一种方法是创建一个自定义 randomGen() 函数,该函数接受最小、最大和所需随机数数量的参数:

<code class="php">function randomGen($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}</code>
登录后复制

要在 PHP 脚本中实现此功能,请使用 randomGen() 生成随机列表 ID 并将其存储在数据库表中。每次刷新页面时,检查生成的列表 ID 是否与存储的值匹配。如果没有,则显示该列表并使用新 ID 更新表格。

此方法可确保所有 20 个列表在发生任何重复之前都显示一次。这是更新的代码片段:

<code class="php"><?php

$businesses = json_decode($data);

$db = new PDO('mysql:host=localhost;dbname=yelp_listings', 'root', 'password');

// Generate a random listing ID using randomGen()
$listing_id = randomGen(1, 20, 1)[0];

// Check if the listing ID matches the stored value
$stmt = $db->prepare('SELECT listing_id FROM shown_listings WHERE id = ?');
$stmt->execute([$listing_id]);

// Display the listing if it hasn't been shown yet
if ($stmt->rowCount() == 0) {
    $business = $businesses->businesses[$listing_id - 1];

    echo "<img border=0 src='" . $business->image_url . "'><br/>";
    echo $business->name . "<br/>";
    echo "<img border=0 src='" . $business->rating_img_url_large . "'><br/>";

    // Add the listing ID to the shown_listings table
    $stmt = $db->prepare('INSERT INTO shown_listings (id) VALUES (?)');
    $stmt->execute([$listing_id]);
}

?></code>
登录后复制

以上是PHP中如何保证随机数唯一且不重复?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!