我正在尝试创建任意长度的随机数,我想制作产品ID和订单ID。但是这里的问题是当我创建新项目给出id 11
的长度时,它将在不改变数字之前使用相同的id。
这是我的PHP代码
<?php
function EventRang($length = 10, $type){
switch($type){
case 'int':
//$keyspace = mt_rand(10000000000, 99999999999).date("Ymd").rand();
$keyspace = str_pad(rand(0, pow(10, $length)-1), $length, '0', STR_PAD_LEFT);
break;
case 'char':
$keyspace = date('Fl').'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'str':
$keyspace = time().'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'oid':
//$keyspace = date("Ymd").time().rand().mt_rand(10000000000, 99999999999);
$keyspace = date("Ymd").time().str_pad(rand(0, pow(10, $length)-1), $length, '0', STR_PAD_LEFT);
break;
default:
$keyspace = time().'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
}
$charactersLength = strlen($keyspace);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $keyspace[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
这始终是输出2147483647
答案 0 :(得分:1)
因为有时答案需要明确
function EventRang($length = 10, $type = 'int') {
// Define the set of characters permitted for the random element for each type
switch($type) {
case 'int':
case 'oid':
$keyspace = '0123456789';
break;
case 'char':
$keyspace = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'str':
default:
$keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
// Generate the random characters/digits
$charactersLength = strlen($keyspace);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $keyspace[rand(0, $charactersLength - 1)];
}
// apply the masking
switch($type) {
case 'int':
return $randomString;
case 'char':
return date('Fl').$randomString;
break;
case 'str':
return time().$randomString;
break;
case 'oid':
return date("Ymd").time().$randomString;
break;
default:
return time().$randomString;
}
}
您需要将屏蔽与键空间分开; keyspace只是用于输出的随机元素的字符集;如果你试图将掩码应用为键空间的一部分,那么你只是倾斜随机性,而不是应用掩码。
另请注意,函数定义也需要类型的默认值,因为它在参数列表中的长度后面,并且length具有默认值