问题
I'm trying to get a function to increment alphas upwards in PHP from say A->ZZ or AAA -> ZZZ with all the variations in between, ie. A, B, C...AA, AB, AC..ZX, ZY, ZZ etc..
The following code works sometimes, but then breaks in certain instances, this example works perfectly.
$from = "A";
$to = "ZZ";
while(strnatcmp($from, $to) <= 0) {
echo $from++;
}
While this does not work as expected.
$from = "A";
$to = "BB";
while(strnatcmp($from, $to) <= 0) {
echo $from++;
}
Output is:
First: A B C D .. AA AB AC .. ZX ZY ZZ
Second: A B
Does any one know what's going on here? or maybe a different approach to my problem. Thanks
回答1:
This works, but it stops on BA
... so you can either say $to = 'BC';
or you can toss in a $to++;
right after you declare $to
.
$from= 'A';
$to = 'BB';
while ($from !== $to) {
echo $from++;
}
$from= 'A';
$to = 'BB';
$to++;
while ($from !== $to) {
echo $from++;
}
If you're using PHP 5.5 you can use a generator.
function alphaRange($from, $to) {
++$to;
for ($i = $from; $i !== $to; ++$i) {
yield $i;
}
}
foreach (alphaRange('A', 'BB') as $char) {
echo $char;
}
回答2:
This should work for you:
<?php
$from = "AA";
$to = "BB";
while(strnatcmp($from, $to) <= 0)
echo $from++ . "<br />";
?>
The Output is:
AA...BB
If you want the Alphabet first too, then copy this before the code from above:
$from = "A";
$to = "Z";
while(strnatcmp($from, $to) <= 0)
echo $from++ . "<br />";
来源:https://stackoverflow.com/questions/27003100/unexpected-behavior-with-strnatcmp-php