我期待根據我擁有的產品數量生成隨機字符串。例如,我有100個名爲「測試」的產品,我希望能夠生成100個產品代碼,這些產品代碼都是唯一的。php中的隨機字符串列表
我目前使用此代碼:
<?php
/**
* The letter l (lowercase L) and the number 1
* have been removed, as they can be mistaken
* for each other.
*/
function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
// Usage
$password = createRandomPassword();
echo "Your random password is: $password";
?>
乾杯
那麼...你的問題是什麼? – Mike 2012-02-17 18:18:14
您需要在某個時間點引用創建的日期時間。您的隨機數字和使用模數不能保證返回一個唯一的值。 – Smamatti 2012-02-17 18:20:16
值得注意的是rand()對於隨機整數是個不錯的選擇 - 查看'mt_rand()'來代替更好的隨機性。另外,看到你刪除l和1,看看只是使用base58 - 這是相似的,但也出於可讀性原因刪除o和0。 – damianb 2012-02-17 23:28:27