在PHP中,如何将Excel样式的列名转换为数字?
使用PHP,如何将Excel样式的列名(如“CF”)转换为数字(CF=84)? 这个问题特别涉及PHP。请不要用另一种语言的答案来“复制”这个功能。试试这些功能在PHP中,如何将Excel样式的列名转换为数字?,php,excel,Php,Excel,使用PHP,如何将Excel样式的列名(如“CF”)转换为数字(CF=84)? 这个问题特别涉及PHP。请不要用另一种语言的答案来“复制”这个功能。试试这些功能 /** * Convert Excel style column names into numbers. * @param string $column Excel style column name like AA or CF * @return integer Number with A being 1 and AA bein
/**
* Convert Excel style column names into numbers.
* @param string $column Excel style column name like AA or CF
* @return integer Number with A being 1 and AA being 27
*/
function alpha2num($column) {
$number = 0;
foreach(str_split($column) as $letter){
$number = ($number * 26) + (ord(strtolower($letter)) - 96);
}
return $number;
}
/**
* Access array value with Excel style column name.
* @param array $array The array to access
* @param string $column Excel style column name like AA or CF
* @return mixed Value found at the column
*/
function alpha_col($array, $column){
$i = alpha2num($column) - 1;
return isset($array[$i]) ? $array[$i] : false;
}
dupe:nogad的可能重复项,但当我搜索解决方案时,我没有找到该问题,因为它是针对另一个实用程序的。@MarianD,它不是该问题的重复项。这个问答特别与PHP的使用有关。哦,你是对的,请接受我的道歉。我看到了,但对我来说,它看起来像是一个肮脏的方法,尽管很健壮。我只是想你可能对他们关于
ord
和strtolower
性能影响的一些观察结果感兴趣。我同意你的方式看起来更整洁。如果你像PHPExcel那样建立一个库,我会更关心性能。当我编写函数时,我正在一个简单的CSV导入系统上工作。这很有意义。我本不想吹毛求疵。我只是想如果你还没看过的话,你会觉得很有趣。