在PHP中将整数转换为字母数字序列[关闭]
I'm working on a url shortener. I based mine on this one https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener and more or less took the function to create the short codes, because i couldn't come up with an algorithm myself:
<?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;
}
?>
Although it works, some of my numbers (database id) output strange shortcodes:
1 -> 2 2 -> 3 ... 10 -> c 11 -> d 12 -> e ...
Is there any easy way i can modify this code, so that my generated short codes are longer than just one character (at least two or three characters for every shortcode), even for integers like 1, 2, 3 etc.?
Also is there anybody who can tell me, how this algorithm above works to output short codes for integers?
Thanks in advance
我正在开发一个url shortener。 我的基础是 https://github.com/phpmasterdotcom/BuildingYourOwnURLShortener ,或多或少采取了 创建短代码的功能,因为我自己无法提出算法: p>
&lt;?php
convertIntToShortCode($ _ GET [“id”]); //测试代码
函数convertIntToShortCode($ id){
$ chars =“123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ”;
$ id = intval($ id);
if if($ id&lt; 1){
echo“ERROR1”;
}
$ length = strlen($ chars);
//确保可用字符的长度至少是合理的最小值 - 应该在
// // 至少10个字符
if($ length&lt; 10){
echo“ERROR2”;
}
$ code =“”;
while($ id&gt; $ length - 1){
//确定下一个较高字符的值
//在短代码中应该是和前面的
$ code = $ chars [fmod($ id,$ length)]。 $ code;
//将$ id重置为要转换的剩余值
$ id = floor($ id / $ length);
}
// $ id的剩余值小于
// self :: $ chars
$ code = $ chars [$ id]。 $ code;
echo $ code;
}
?&gt;
code> pre>
虽然它有效,但我的一些数字(数据库ID)输出奇怪 短代码: p>
1 - &gt; 2
2 - &gt; 3
...
10 - &gt; c
11 - &gt; d
12 - &gt; e
... p>
有没有简单的方法可以修改这段代码,这样我生成的短代码只比一个字符长(每个短代码至少有两三个字符) ),即使对于1,2,3等整数? p>
还有谁能告诉我,上面这个算法如何输出整数的短代码? p>
提前致谢 p>
div>
What you would like to do is convert that number to a different notation - one that includes both letters and numbers like base 36 which is actually alphanumeric -> a-z + 0-9.
So what you would need to do is:
$string = base_convert ( $number , 10, 36 );
Documentation:
string base_convert ( string $number , int $frombase , int $tobase );