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學習者快速成長!