嗨我有一个生成随机字符串的函数,但是我想设置3个前缀&s;和system来选择指定的随机前缀?前缀是001,002或003.例如,当我尝试生成字符串时,我希望我的系统选择我指定的这些前缀。
public function generateRandomNumber($length) {
$prefix = '001';
//$prefix = '001';
//$prefix = '001';
$characters = '0123456789';
$charactersLength = strlen($characters);
$randomNumber = '';
for ($i = 0; $i < $length; $i++) {
$randomNumber .= $characters[rand(0, $charactersLength - 1)];
}
return $prefix . $randomNumber;
}
答案 0 :(得分:2)
您可以使用array_rand
创建一个前缀数组并选择一个随机数。
$prefixes = ['001', '002', '003'];
$prefix = $prefixes[array_rand($prefixes)];
答案 1 :(得分:2)
public function generateRandomNumber($length) {
$prefix = array(001,002,003);
$characters = '0123456789';
$charactersLength = strlen($characters);
$randomNumber = '';
for ($i = 0; $i < $length; $i++) {
$randomNumber .= $characters[rand(0, $charactersLength - 1)];
}
return $prefixes[array_rand($prefixes)].$randomNumber;
}