3

Hi i have the table structure as follows

id   --auto increment id
alphabet
user_id
name

and while adding i needs to insert the english alphabets to users as incremental order like this A,B,C,....Z,AA,AB,AC,...AZ,BA,BB,BC,.....BZ.

I need to get like this

    id    alphabet  user_id   name  
------------------------------------------
    1      A          1       name-1
    2      B          1       name-2
    .      .          .         .
    .      .          .         .
    26     Z          1       name-n
    27     A          2       name-1
    28     B          2       name-2
    .      .          .         .
    .      .          .         .
    52     Z          2       name-52
    53     AA         2       name-53 
    .      .          .         .
    .      .          .         .
    .      .          .         .
    .      AZ         2         .  

Thanks for your time.

iLaYa ツ
  • 3,941
  • 3
  • 32
  • 48

3 Answers3

1

Check this similar article:

Algorithm to get the excel-like column name of a number

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;
    }
}

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;
    }
}

Tested with numbers from 0 to 10000...

Community
  • 1
  • 1
Vijay Joseph
  • 492
  • 3
  • 14
1

It's quite easy that you use php to implement this, please check codes below

$i = 'A';
echo $i;
echo PHP_EOL;
while($i != 'ZZ')
{
 echo ++$i;
 echo PHP_EOL;
}

or see the results in http://codepad.org/QB4kyV7U

Lake
  • 813
  • 4
  • 6
0

Sounds a lot like this SO article

MYSQL: how to "reorder" a table

Is there an absolute necessity to do what you are wanting when you can use sorting to output your data however you want?

Community
  • 1
  • 1
rws907
  • 787
  • 4
  • 14
  • 25