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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路