問題描述
我正在開發(fā)一個活動組織網(wǎng)站.在這里,當用戶注冊活動時,他將獲得一個唯一的隨機數(shù)(10 位),我們用它來生成條形碼并將其郵寄給他.現(xiàn)在,
I am developing a event organization website. Here when the user registers for an event he will be given a unique random number(10 digit), which we use to generate a barcode and mail it to him. Now,
- 我想為每個注冊的活動設(shè)置唯一的編號.
- 也是隨機的
一種解決方案是獲取數(shù)組中的所有隨機數(shù)并使用 Php rand(1000000000, 9999999999) 生成一個隨機數(shù),然后循環(huán)并檢查所有值.獲取不等于數(shù)組中任何值的第一個值并將其添加到數(shù)據(jù)庫中.
One solution is to grab all the random numbers in an array and generate a random number using Php rand(1000000000, 9999999999) and loop through and check all the values. Grab the first value that doesn't equal to any of the values in the array and add it to the database.
但我認為可能有更好的解決方案.有什么建議嗎?
But I am thinking that there might be a better solution to this. Any suggestion?
推薦答案
您的邏輯在技術(shù)上沒有問題.但是,如果您的應用程序吸引了大量用戶,那么在資源和計算時間方面,獲取所有隨機數(shù)可能會變得不必要地昂貴.
Your logic isn't technically faulty. However, if your application attracts lots of users, fetching all of the random numbers may well become unnecessarily expensive, in terms of resources and computation time.
我建議另一種方法,即生成一個隨機數(shù),然后根據(jù)數(shù)據(jù)庫進行檢查.
I would suggest another approach, where you generate a random number and then check it against the database.
function generateBarcodeNumber() {
$number = mt_rand(1000000000, 9999999999); // better than rand()
// call the same function if the barcode exists already
if (barcodeNumberExists($number)) {
return generateBarcodeNumber();
}
// otherwise, it's valid and can be used
return $number;
}
function barcodeNumberExists($number) {
// query the database and return a boolean
// for instance, it might look like this in Laravel
return User::whereBarcodeNumber($number)->exists();
}
這篇關(guān)于如何在laravel中為每個用戶生成唯一的隨機值并將其添加到數(shù)據(jù)庫中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!