問題描述
我正在編寫一個生成一些 Excel 文檔的腳本,我需要將一個數(shù)字轉(zhuǎn)換為其等效的列名.例如:
I'm working on a script that generate some Excel documents and I need to convert a number into its column name equivalent. For example:
1 => A
2 => B
27 => AA
28 => AB
14558 => UMX
我已經(jīng)編寫了一個算法來這樣做,但我想知道是否有更簡單或更快的方法來做到這一點:
I have already written an algorithm to do so, but I'd like to know whether are simpler or faster ways to do it:
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;
}
你知道更好的方法嗎?也許是為了讓它更簡單?還是性能改進?
Do you know a better way to do it? Maybe something to keep it simpler? or a performance improvement?
ircmaxell 的實現(xiàn)效果很好.但是,我要添加這個簡短的內(nèi)容:
ircmaxell's implementation works pretty fine. But, I'm going to add this nice short one:
function num2alpha($n)
{
for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
$r = chr($n%26 + 0x41) . $r;
return $r;
}
推薦答案
這是一個很好的簡單遞歸函數(shù)(基于零索引數(shù),意思是 0 == A、1 == B 等)...
Here's a nice simple recursive function (Based on zero indexed numbers, meaning 0 == A, 1 == B, etc)...
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,等等):
And if you want it one indexed (1 == A, etc):
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 的數(shù)字進行測試...
Tested with numbers from 0 to 10000...
這篇關(guān)于獲取數(shù)字的類似excel的列名的算法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!