我希望根据我拥有的产品数量生成一个随机字符串。例如,我有100个名为"测试"的产品,我希望能够生成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";
?>
干杯
使用您的函数可以生成100个随机字符串,即
$product_names = array ();
for ($i=0; $i < 10; $i++ )
$product_names[] = "code-" . createRandomPassword();
print_r ( $product_names );
不过你的问题还不清楚。您是否有要遵循的命名约定,是否要以模式生成代码,如"product1"、"product2"、…、"产品100'等?
编辑:上面的代码创建以下输出:
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
)
已经有一个内置函数可以为您轻松处理此问题。CCD_ 1基于以微秒为单位的当前时间生成带前缀的唯一标识符。
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);
}
?>
值得注意的是,为了确保真正的唯一性,您需要存储所有生成的代码,并检查是否没有发出重复的代码。