【问题标题】:How to generate unique 6 digit code如何生成唯一的 6 位代码
【发布时间】:2017-06-17 17:56:14
【问题描述】:

我想生成 6 位唯一代码,但我希望前 3 个是字母,后 3 个是数字,如下例所示..

AAA111
ABD156
DFG589
ERF542...

请帮助创建具有上述组合的代码..

下面是我的代码..

public function generateRandomString()  {
        $characters = '1234567890';
        $length = 6;
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

【问题讨论】:

  • 您已经接受了答案,但我已对其进行了更新以提高效率。
  • 您可能希望使用Random::alphaUppercaseString(3)Random::intBetween(100, 999) 连接(带点)。

标签: php string random


【解决方案1】:

您希望前 3 个字符为字母,后 3 个字符为数字?那么你应该分别处理它们。

function genRandStr(){
  $a = $b = '';

  for($i = 0; $i < 3; $i++){
    $a .= chr(mt_rand(65, 90)); // see the ascii table why 65 to 90.    
    $b .= mt_rand(0, 9);
  }

  return $a . $b;
}

您还可以使用函数参数来添加动态性,对于随机顺序,您可以执行以下操作:

// PHP >= 7 code
function genRandStr(int $length = 6, string $prefix = '', string $suffix = ''){
  for($i = 0; $i < $length; $i++){
    $prefix .= random_int(0,1) ? chr(random_int(65, 90)) : random_int(0, 9);
  }

  return $prefix . $suffix;
}

对于 PHP 版本 mt_rand(),否则建议使用 random_int()

您仍然需要检查可能的冲突并将其放入 while 循环中。

【讨论】:

  • 我有点喜欢这种方法...也许使它更具可读性的一种方法是在生成字母时使用chr(mt_rand(ord('A'), ord('Z')))
  • 本质上,这只会增加 6 个额外的函数调用,但会使代码对人眼更具可读性。
【解决方案2】:
function generateRandomString()  {
    $letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $digits = '1234567890';
    $randomString = '';
    for ($i = 0; $i < 3; $i++) {
        $randomString .= $letters[rand(0, strlen($letters) - 1)];
    }
    for ($i = 0; $i < 3; $i++) {
        $randomString .= $digits[rand(0, strlen($digits) - 1)];
    }
    return $randomString;
}

http://sandbox.onlinephpfunctions.com/code/ec0b494c4e08ab220fe7601504c8611459690c33

【讨论】:

  • 因为我欣赏体育精神,+1。您的代码完成这项工作仍然很有效。
【解决方案3】:

请检查以下代码:

<?php
    $string1 = str_shuffle('abcdefghijklmnopqrstuvwxyz');
    $random1 = substr($string1,0,3);
    $string2 = str_shuffle('1234567890');
    $random2 = substr($string2,0,3);

    echo $random = $random1.$random2;
?>

【讨论】:

  • 使用这种方法的一个潜在缺点是不会有任何重复的字母或数字。
猜你喜欢
  • 2013-05-04
  • 2012-04-05
  • 2011-07-24
  • 2011-07-19
  • 2017-11-07
  • 2015-07-29
  • 2011-08-19
  • 2011-08-20
  • 2019-06-17
相关资源
最近更新 更多