<分区>
我正在研究一个网址缩短器。我基于这个 https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener 并或多或少地使用了创建短代码的功能,因为我自己无法想出一种算法:
<?php
convertIntToShortCode($_GET["id"]); // Test codes
function convertIntToShortCode($id) {
$chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
$id = intval($id);
if ($id < 1) {
echo "ERROR1";
}
$length = strlen($chars);
// make sure length of available characters is at
// least a reasonable minimum - there should be at
// least 10 characters
if ($length < 10) {
echo "ERROR2";
}
$code = "";
while ($id > $length - 1) {
// determine the value of the next higher character
// in the short code should be and prepend
$code = $chars[fmod($id, $length)] . $code;
// reset $id to remaining value to be converted
$id = floor($id / $length);
}
// remaining value of $id is less than the length of
// self::$chars
$code = $chars[$id] . $code;
echo $code;
}
?>
虽然它有效,但我的一些数字(数据库 ID)输出了奇怪的简码:
1 -> 2 2 -> 3 ... 10 -> 丙 11 -> d 12 -> 电子 ...
有什么简单的方法可以修改此代码,使我生成的短代码长于一个字符(每个短代码至少两个或三个字符),即使对于 1、2、3 等整数也是如此?
还有谁能告诉我,上面的算法如何输出整数的短代码?
提前致谢