不管使用任何语言,循环时经常用到的一种语法,首先我们先看一下下边的这个程序:


    for($i='A'; $i<='Z'; $i++)
    {
        echo $i . '';
    }
?>

他的执行结果并不是 A B … Y Z 而是 A B … Y Z AA AB … ZY ZZ

可能预想的结果不太一样,为什么会有这样的结果的。在PHP手册中“递增/递减运算符”一节有过描述:

PHP follows Perl’s convention when dealing with arithmetic operations on character variables and not C’s. For example, in PHP and Perl $a = ‘Z’; $a++; turns $a into ‘AA’, while in C a = ‘Z’; a++; turns a into ‘[’ (ASCII value of ‘Z’ is 90, ASCII value of ‘[’ is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

在处理字符变量的算数运算时,PHP 沿袭了 Perl 的习惯,而非 C 的。例如,在 Perl 中 $a = ‘Z’; $a++; 将把 $a 变成’AA’,而在 C 中,a = ‘Z’; a++; 将把 a 变成 ‘[’(‘Z’ 的 ASCII 值是 90,’[’ 的 ASCII 值是 91)。注意字符变量只能递增,不能递减,并且只支持纯字母(a-z 和 A-Z)。递增/递减其他字符变量则无效,原字符串没有变化。

因此,基于PHP 沿袭了 Perl 的习惯,我们可以轻易的去生成 excel 的表格头部。

版本一

利用 range 方法生成 A B … Y Z

range('A', 'Z')

版本二

生成 A B … Y Z AA AB … ZY ZZ

for($i='A'; strlen($i)<3; $i++) {
    var_dump($i);
}

版本三

生成 A B … Y Z AA AB … BY BZ,当然可以根据修改 $i!='CA' 来控制生成的数量

for($i='A'; $i!='CA'; $i++) {
    var_dump($i);
}

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!