php:将数字转换为字母表,反之亦然
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7664121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php: converting number to alphabet and vice versa
提问by pillarOfLight
So I have this function:
所以我有这个功能:
function toAlpha($data){
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alpha_flip = array_flip($alphabet);
if($data <= 25){
return $alphabet[$data];
}
elseif($data > 25){
$dividend = ($data + 1);
$alpha = '';
$modulo;
while ($dividend > 0){
$modulo = ($dividend - 1) % 26;
$alpha = $alphabet[$modulo] . $alpha;
$dividend = floor((($dividend - $modulo) / 26));
}
return $alpha;
}
}
which given a number converts it into character and it works fine
给定一个数字将其转换为字符并且它工作正常
but then I also want a reverse function of this that given any output of this function, return the exact input that was put in to produce that output and I tried this:
但后来我也想要一个反向函数,给出这个函数的任何输出,返回产生该输出的确切输入,我试过这个:
function toNum($data){
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$alpha_flip = array_flip($alphabet);
if(strlen($data) == 1){
return (isset($alpha_flip[$data]) ? $alpha_flip[$data] : FALSE);
}
else if(strlen($data) > 1){
$num = 1;
for($i = 0; $i < strlen($data); $i++){
if(($i + 1) < strlen($data)){
$num *= (26 * ($alpha_flip[$data[$i]] + 1));
}
else{
$num += ($alpha_flip[$data[$i]] + 1);
}
}
return ($num + 25);
}
}
but it's not working properly...toAlpha(728) is producing 'aba' but toNum('aba') is producing 1378 rather than 728...
但它不能正常工作...... toAlpha(728) 正在生成 'aba' 但 toNum('aba') 正在生成 1378 而不是 728 ...
what did I do wrong? how can I fix the reverse function so that it works properly?
我做错了什么?如何修复反向功能以使其正常工作?
thanks in advance!
提前致谢!
采纳答案by Hammerite
I don't understand at all the logic you're trying to use in that function. What you're trying to do seems very strange (why does 'a' map to zero and yet 'aa' maps to 26?), but this appears to work. (You will want to use some more test cases, I only checked that it gives the correct output for the case 'aba'.)
我完全不明白您试图在该函数中使用的逻辑。你试图做的事情看起来很奇怪(为什么 'a' 映射到 0 而 'aa' 映射到 26?),但这似乎有效。(您将需要使用更多测试用例,我只检查了它是否为案例 'aba' 提供了正确的输出。)
function toNum($data) {
$alphabet = array( 'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z'
);
$alpha_flip = array_flip($alphabet);
$return_value = -1;
$length = strlen($data);
for ($i = 0; $i < $length; $i++) {
$return_value +=
($alpha_flip[$data[$i]] + 1) * pow(26, ($length - $i - 1));
}
return $return_value;
}
回答by Cyril
Shortest way, in PHP >= 4.1.0
最短的方式,在 PHP >= 4.1.0
$alphabet = range('A', 'Z');
echo $alphabet[3]; // returns D
echo array_search('D', $alphabet); // returns 3
回答by sara_thepot
From number to alphabet (with A=0, B=1, etc...):
从数字到字母表(A=0、B=1 等...):
function toAlpha($num){
return chr(substr("000".($num+65),-3));
}
You can do the same from alphabet to number with the function ord()
.
您可以使用函数从字母到数字执行相同的操作ord()
。
Changing 65 with 97, you can obtain the lowercase values.
将 65 改为 97,您可以获得小写值。
回答by Mason Barge
Your problems comes from your map. Look at this:
你的问题来自你的地图。看这个:
$alpha[0] = 'Alphabet';
for ($i = 'a'; $i<'z'; $i++) {
$alpha[] = $i;
}
$alpha[26] = 'z';
You can run this as high as you want and your server memory will allow. The PHP is buggy, and (at least on my server) if you use the <= operator:
您可以根据需要运行它,并且您的服务器内存允许。PHP 有问题,并且(至少在我的服务器上)如果您使用 <= 运算符:
$alpha[0] = 'Alphabet';
for ($i = 'a'; $i<='z'; $i++) {
$alpha[] = $i;
}
then it will map all the way to [676]=> string(2) "yz"! You just have to play with it.
然后它会一直映射到 [676]=> string(2) "yz"!你只需要玩它。
I didn't want to map a letter to [0] so I just put a title in there. Obviously you can leave it out if you want 0=>a, 1=>b, etc.
我不想将一个字母映射到 [0] 所以我只是在那里放了一个标题。显然,如果您想要 0=>a、1=>b 等,您可以省略它。
Once the array is correct, the function is trivial.
一旦数组正确,函数就变得微不足道了。
回答by Praveen
to convert number to alphacode
for example: 1402 to bax
将数字转换为字母代码
例如:1402转bax
function number_to_alpha($num, $code)
{
$alphabets = array('', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$division = floor($num / 26);
$remainder = $num % 26;
if($remainder == 0)
{
$division = $division - 1;
$code .= 'z';
}
else
$code .= $alphabets[$remainder];
if($division > 26)
return number_to_alpha($division, $code);
else
$code .= $alphabets[$division];
return strrev($code);
}
to convert alphacode to number
for example: bax to 1402
将字母代码转换为数字
例如:bax 到 1402
function alpha_to_number($code)
{
$alphabets = array('', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$sumval = 0;
$code = strtolower(trim($code));
$arr = str_split($code);
$arr_length = count($arr);
for($i = 0, $j = $arr_length-1; $i < $arr_length; $i++, $j--)
{
$arr_value = array_search($arr[$i], $alphabets);
$sumval = $sumval + ($arr_value * pow(26, $j));
}
return $sumval;
}
回答by rvbarreto
Using Cyril's answer, I elaborated a bit for a case with more than one letter.
使用 Cyril 的回答,我详细阐述了一个不止一个字母的案例。
function lettersToNumber($letters){
$alphabet = range('A', 'Z');
$number = 0;
foreach(str_split(strrev($letters)) as $key=>$char){
$number = $number + (array_search($char,$alphabet)+1)*pow(count($alphabet),$key);
}
return $number;
}
A few results for the function are displayed bellow:
该函数的一些结果如下所示:
lettersToNumber("A"); //returns 1
lettersToNumber("E"); //returns 5
lettersToNumber("Z"); //returns 26
lettersToNumber("AB"); //returns 28
lettersToNumber("AP"); //returns 42
lettersToNumber("CE"); //returns 83
回答by Dr. Sassafras
I took the 'corrected' original, removed the debug code, and other unnecessary code, modified it so it will work with any number of characters. For example, Greek only has 24 characters.
我采用了“更正”的原件,删除了调试代码和其他不必要的代码,对其进行了修改,以便它可以处理任意数量的字符。例如,希腊语只有 24 个字符。
function toAlpha($number, $alphabet)
{
$count = count($alphabet);
if ($number <= $count) {
return $alphabet[$number - 1];
}
$alpha = '';
while ($number > 0) {
$modulo = ($number - 1) % $count;
$alpha = $alphabet[$modulo] . $alpha;
$number = floor((($number - $modulo) / $count));
}
return $alpha;
}
toAlpha(45,range('a','z'));
And here are some examples of ranges:
以下是范围的一些示例:
// lower greek
$range = ['α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω'];
// upper greek
$range = ['Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω'];
// georgian
$range = ['?' => 10000, '?' => 9000, '?' => 8000, '?' => 7000, '?' => 6000, '?' => 5000, '?' => 4000, '?' => 3000, '?' => 2000, '?' => 1000, '?' => 900, '?' => 800, '?' => 700, '?' => 600, '?' => 500, '?' => 400, '?' => 300, '?' => 200, '?' => 100, '?' => 90, '?' => 80, '?' => 70, '?' => 60, '?' => 50, '?' => 40, '?' => 30, '?' => 20, '?' => 10, '?' => 9, '?' => 8, '?' => 7, '?' => 6, '?' => 5, '?' => 4, '?' => 3, '?' => 2, '?' => 1];
回答by user414873
There is a very clever solution by Theriault in the comments of PHPs base_convert function
在PHP 的 base_convert 函数的注释中,Theriault 有一个非常聪明的解决方案
/**
* Converts an integer into the alphabet base (A-Z).
*
* @param int $n This is the number to convert.
* @return string The converted number.
* @author Theriault
*
*/
function num2alpha($n) {
$r = '';
for ($i = 1; $n >= 0 && $i < 10; $i++) {
$r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
$n -= pow(26, $i);
}
return $r;
}
/**
* Converts an alphabetic string into an integer.
*
* @param int $n This is the number to convert.
* @return string The converted number.
* @author Theriault
*
*/
function alpha2num($a) {
$r = 0;
$l = strlen($a);
for ($i = 0; $i < $l; $i++) {
$r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
}
return $r - 1;
}
回答by Santosh Pradhan
Here is a fix to original function toAlpha. It is not working for toAlpha(27)
这是对原始函数 toAlpha 的修复。它不适用于 toAlpha(27)
function toAlpha($n,$case = 'upper'){
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$n = $n-1;
Util::error_log('N'.$n);
if($n <= 26){
$alpha = $alphabet[$n-1];
} elseif($n > 26) {
$dividend = ($n);
$alpha = '';
$modulo;
while($dividend > 0){
$modulo = ($dividend - 1) % 26;
$alpha = $alphabet[$modulo].$alpha;
$dividend = floor((($dividend - $modulo) / 26));
}
}
if($case=='lower'){
$alpha = strtolower($alpha);
}
Util::error_log("**************".$alpha);
return $alpha;
}
回答by paul4156
function toNum($str) {
$num = 0;
for ($i = 0; $i < strlen($str); $i++) {
$num += ord($str[$i]);
$num *= 26;
}
return $num;
}
function toStr($num) {
$str = '';
while ($num > 0) {
$str = chr($num % 26) . $str;
$num = (int) ($num / 26);
}
return $str;
}