我正在编写一个生成一些Excel文档的脚本,我需要将一个数字转换为其对应的列名.例如:

1 => A
2 => B
27 => AA
28 => AB
14558 => UMX

我已经为此编写了一个算法,但我想知道是否有更简单或更快的方法来做到这一点:

function numberToColumnName($number){
    $abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $abc_len = strlen($abc);

    $result_len = 1; // how much characters the column's name will have
    $pow = 0;
    while( ( $pow += pow($abc_len, $result_len) ) < $number ){
        $result_len++;
    }

    $result = "";
    $next = false;
    // add each character to the result...
    for($i = 1; $i<=$result_len; $i++){
        $index = ($number % $abc_len) - 1; // calculate the module

        // sometimes the index should be decreased by 1
        if( $next || $next = false ){
            $index--;
        }

        // this is the point that will be calculated in the next iteration
        $number = floor($number / strlen($abc));

        // if the index is negative, convert it to positive
        if( $next = ($index < 0) ) {
            $index = $abc_len + $index;
        }

        $result = $abc[$index].$result; // concatenate the letter
    }
    return $result;
}

你知道做这件事的更好方法吗?也许有什么能让事情变得简单些?或者是性能提升?

编辑

ircmaxell的实现工作得很好.但是,我要加上这个漂亮的短的:

function num2alpha($n)
{
    for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
        $r = chr($n%26 + 0x41) . $r;
    return $r;
}

推荐答案

这是一个很好的简单递归函数(基于零索引数,意思是0==a,1==B,等等)...

function getNameFromNumber($num) {
    $numeric = $num % 26;
    $letter = chr(65 + $numeric);
    $num2 = intval($num / 26);
    if ($num2 > 0) {
        return getNameFromNumber($num2 - 1) . $letter;
    } else {
        return $letter;
    }
}

如果你想给它编一个索引(1==A,等等):

function getNameFromNumber($num) {
    $numeric = ($num - 1) % 26;
    $letter = chr(65 + $numeric);
    $num2 = intval(($num - 1) / 26);
    if ($num2 > 0) {
        return getNameFromNumber($num2) . $letter;
    } else {
        return $letter;
    }
}

用0到10000的数字进行测试...

Php相关问答推荐

Laravel变形 map 不适用于扩展模型

更新WooCommerce高性能订单存储(HPOS)的管理员自定义订单元数据

PHP在将数组子集赋给变量时是否复制数组子集?

在WooCommerce中处理客户总支出中的退款

Laravel迁移返回SQL错误,但SQL有效且工作正常

根据未用于变体的产品属性隐藏WooCommerce发货方式

PHP根据特定索引值从中删除子数组

Laravel区分大小写搜索

htaccess重命名index.php以在URL中显示为SEO的友好名称

Laravel自定义验证规则更正

登录后重定向在WooCommerce中购买产品的用户

以编程方式同步 WPML 翻译更改 Woocommerce 产品销售价格

打折时更改 Woocommerce 产品名称

既然setSQLLogger()已被弃用,如何使用中间件在 Doctrine 3 中记录查询执行时间?

invalid_grant 和无效的 JWT 签名

用自定义代码替换 WooCommerce 单一产品简短描述

当我激活插件时出现错误注意:未定义的偏移量:1

正则表达式将文本替换为标签 html 以字符开头

后退按钮不起作用 laravel ajax crud

NetBeans 不显示中文内容