2014-09-21 74 views
2

我知道如何从一个列表到Z:如何从一个列表到Z在PHP中,然后就到AA,AB,AC,等

foreach (range('A', 'Z') as $char) { 
    echo $char . "\n"; 
} 

但是我怎么去从那里列表AA,AB,AC,AD,... AZ,BA,BB,BC等?

我做了一个快速的谷歌搜索,找不到任何东西,但我想这种方法会有所不同。

我想我可以通过使用for循环和一个内部带有字母的数组来实现,尽管这种方式看起来有点粗俗。

还有其他方法吗?

谢谢。

+0

如何使用您的代码示例作为胚胎的递归函数? – 2014-09-21 11:06:27

回答

10

PHP有字符串增量操作者正是这么做的:

for($x = 'A'; $x < 'ZZ'; $x++) 
    echo $x, ' '; 

结果:

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 AA AB AC AD AE AF... 

编号:

PHP在处理字符变量而不是C的算术运算时遵循Perl的惯例。例如,在PHP和Perl中$ a ='Z'; $ A ++;将$ a变成'AA',而在C a ='Z'中;一个++;将a变成'['('Z'的ASCII值是90,'['的ASCII值是91)。请注意,字符变量可以递增但不递减,即使如此,只支持纯ASCII字母和数字(a-z,A-Z和0-9)。递增/递减其他字符变量不起作用,原始字符串不变。

http://php.net/manual/en/language.operators.increment.php

+1

哇 - 真的没想到。 – think123 2014-09-21 11:12:00

+0

不得不说,它适用于上述情况,但是当您尝试使用for(例如,$ x ='A'; $ x <'AZ'; $ x ++)'时,它会中断。 – think123 2014-09-21 11:14:49

+1

@ think123:用'!='替换'<'=' – georg 2014-09-21 11:15:34

2

尝试

foreach (range('A', 'Z') as $char) { 
    foreach (range('A', 'Z') as $char1) { 
     echo $char . $char1. "\n"; 
    } 
} 
+0

我想你错过了最后一部分***等等?***。 – 2014-09-21 11:08:07

+0

嗯,sorta的作品 - 但这将如何给我A,B,C ... Z第一? – think123 2014-09-21 11:09:44

0

我搞砸了一下周围,并得到了这一点:

$addon = 64; 
for ($i = 1; $i <= 700; $i++) { 
    $prefix = ""; 
    if ($i > 26) { 
    $remainder = floor($i/26); 
    $prefix = chr($remainder + $addon); 
    } 
    $ivalue = ($i % 26 == 0) ? 26 : $i % 26; 
    echo $prefix . chr($addon + $ivalue) . "<br />"; 
} 

$addon是64,至于字符代码为65,这意味着我们只想补充一点,从A到Z的工作。直到ZZ工作 - 随意使它适用于AAA,AAB,AAC等。

0

使用此递归函数来从A得到确切范围AC

您可以使用此为Excel列表也喜欢

function myRange($end_column = '', $first_letters = '') { 
    $columns = array(); 
    $length = strlen($end_column); 
    $letters = range('A', 'Z'); 

    // Iterate over 26 letters. 
    foreach ($letters as $letter) { 
     // Paste the $first_letters before the next. 
     $column = $first_letters . $letter; 
     // Add the column to the final array. 
     $columns[] = $column; 
     // If it was the end column that was added, return the columns. 
     if ($column == $end_column) 
      return $columns; 
    } 

    // Add the column children. 
    foreach ($columns as $column) { 
     // Don't itterate if the $end_column was already set in a previous itteration. 
     // Stop iterating if you've reached the maximum character length. 
     if (!in_array($end_column, $columns) && strlen($column) < $length) { 
      $new_columns = myRange($end_column, $column); 
      // Merge the new columns which were created with the final columns array. 
      $columns = array_merge($columns, $new_columns); 
     } 
    } 

    return $columns; 
} 

通话功能。

print_r(myRange('AC')); 

会给你造成

一个 乙 Ç 。 。 。 AA AB AC

相关问题