我想生成字母数字唯一数字,但格式应该是这样的
在AB001到AB999之后应该从AA001到AA999开始...... BA001到BA999以ZZ999结束。如果我给出输入 1 = result AA001
999 = result AA999
1000 = result AB001
任何人都可以帮忙吗?
答案 0 :(得分:6)
完整解决方案(see it running):
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";
}
注意:您需要确保输入的数字在有效范围内(包括000号码时为0 ... 675999,否则为1 ... 675324)
注意:回答修改,错过了之前不允许000的点
答案 1 :(得分:3)
怎么样:
$start = 'AA997';
for($i = 0; $i < 5; $i++) {
$start++;
if (substr($start, 2) == '000') continue;
echo $start,"\n";
}
<强>输出:强>
AA998
AA999
AB001
AB002