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...
What did I do wrong? Ho开发者_JAVA百科w can I fix the reverse function so that it works properly?
Shortest way, in PHP >= 4.1.0
$alphabet = range('A', 'Z');
echo $alphabet[3]; // returns D
echo array_search('D', $alphabet); // returns 3
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'.)
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;
}
There is a very clever solution by Theriault in the comments of PHPs base_convert function
/**
* 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;
}
From number to alphabet (with A=0, B=1, etc...):
function toAlpha($num){
return chr(substr("000".($num+65),-3));
}
You can do the same from alphabet to number with the function ord()
.
Changing 65 with 97, you can obtain the lowercase values.
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:
$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.
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.
Once the array is correct, the function is trivial.
Using Cyril's answer, I elaborated a bit for a case with more than one letter.
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
to convert number to alphacode
for example: 1402 to 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
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;
}
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.
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];
Here is a fix to original function toAlpha. It is not working for 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;
}
We can convert our number from decimal (base 10) to alphanumeric (base 36) and shift the position from the numeric block to alphabetic block using base_convert()
:
function toLetter(int $num) {
return strtoupper(base_convert($num + 9, 10, 36));
}
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;
}
精彩评论