Best way to list Alphabetical(A-Z) using PHP

前端 未结 11 2073
迷失自我
迷失自我 2020-12-13 13:33

I need to print/list alphabetical(A-Z) chararcters to manage Excel cells. Is there any PHP function to list alphabetic?

I need result as

A1
B1
C1
D1
..         


        
11条回答
  •  执念已碎
    2020-12-13 13:47

    I made a constant time function as follows

    This function gives the Alphabetic representation of a numeric index

    public static $alpha = ['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'];
    
    public static function getColName($index){
      $index--;
      $nAlphabets = 26;
      $f = floor($index/pow($nAlphabets,0)) % $nAlphabets;
      $s = (floor($index/pow($nAlphabets,1)) % $nAlphabets)-1;
      $t = (floor($index/pow($nAlphabets,2)) % $nAlphabets)-1;
    
      $f = $f < 0 ? '' : self::$alpha[$f];
      $s = $s < 0 ? '' : self::$alpha[$s];
      $t = $t < 0 ? '' : self::$alpha[$t];
    
      return trim("{$t}{$s}{$f}");
    
    }
    

    Now if you want to use it create a range. you can call this function in a loop pushing your values to an array.

    As for most of the time, we need the representation rather than a range this function would work just fine.

    HOW TO USE

    Just enclose these static functions in a class and use it as

    className::getColName(47);
    

    Making a range in my case was a waste of memory.

提交回复
热议问题