我希望根据我拥有的产品数量生成随机字符串。例如,我有100个名为“test”的产品我希望能够生成100个产品代码,这些代码都是唯一的。
我目前正在使用此代码:
<?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";
?>
干杯
答案 0 :(得分:2)
使用您的函数,您可以生成100个随机字符串,即
$product_names = array ();
for ($i=0; $i < 10; $i++ )
$product_names[] = "code-" . createRandomPassword();
print_r ( $product_names );
但你的问题并不清楚。您是否有要遵循的命名约定,是否要生成模式中的代码,例如'product1','product2',...,'product100'等?
编辑:上面的代码创建了以下输出:
Array
(
[0] => code-opt6ggji
[1] => code-4qfjt653
[2] => code-8ky4xxo0
[3] => code-dfip2o5x
[4] => code-3e3irymv
[5] => code-dgqk0rzt
[6] => code-3fbeq0gr
[7] => code-tev7fbwo
[8] => code-idg04mdm
[9] => code-8c2uuvsj
)
答案 1 :(得分:1)
已经有一个内置函数可以为您轻松处理这个问题。 uniqid
根据当前时间(以微秒为单位)生成带前缀的唯一标识符。
http://php.net/manual/en/function.uniqid.php
<?php
// loop 100 times
for ($i=0; $i<100; $i++)
{
// print the uniqid based on 'test'
echo uniqid('test', true);
}
?>
值得注意的是,为了确保真正的唯一性,您需要存储生成的所有代码并检查是否没有发布重复。