生成字母数字唯一的数字


Generate alphanumeric unique numbers

我想生成字母数字的唯一数字,但格式应该是这样的

应该从AA001到AA999开始,然后是AB001到AB999 ....BA001 ~ BA999以ZZ999结尾。如果输入是

  1 = result AA001
 999  = result AA999
 1000 = result AB001 

有人能帮忙吗?

完整解决方案(参见运行):

function formatNum1000($num) {
  $tail =       $num % 1000;
  $head = (int)($num / 1000);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));
  return sprintf('%s%s%03d', $char1, $char2, $tail);
}
function formatNum999($num) {
  $tail =      (($num - 1    ) % 999) + 1;
  $head = (int)(($num - $tail) / 999);
  $char1 = chr(ord('A') + (int)($head / 26));
  $char2 = chr(ord('A') +      ($head % 26));
  return sprintf('%s%s%03d', $char1, $char2, $tail);
}
$ns = array(1, 500, 999, 1000, 1998, 1999, 2000, 25974, 25975, 25999, 26000, 675324, 675999);
foreach($ns as $n) {
  $formatted1000 = formatNum1000($n);
  $formatted999  = formatNum999 ($n);
  echo "Num: $n => $formatted1000 / $formatted999'n";
}

注意: 您需要确保输入的数字在有效范围内(0…675999当包含000-number时,1…675324否则)

注释:修改后的答案,忽略了前面的点,000是不允许的

如何:

$start = 'AA997';
for($i = 0; $i < 5; $i++) {
    $start++;
    if (substr($start, 2) == '000') continue;
    echo $start,"'n";
}
输出:

AA998
AA999
AB001
AB002