ds19891231 2014-02-14 13:18
浏览 62
已采纳

在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

  • 写回答

1条回答 默认 最新

  • dongqiu3254 2014-02-14 13:26
    关注

    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 );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答