strnatcmp()PHP的异常行为 [英] Unexpected behavior with strnatcmp() PHP

查看:38
本文介绍了strnatcmp()PHP的异常行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从PHP中说A-> ZZ或AAA-> ZZZ向上增加Alpha的功能,并且之间存在所有变化. A,B,C ... AA,AB,AC..ZX,ZY,ZZ等.

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++;
}

输出为:

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

推荐答案

此方法有效,但它会在BA上停止...因此,您可以说$to = 'BC';,也可以在之后紧接着扔$to++;声明$to.

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++;
}

如果您使用的是PHP 5.5,则可以使用生成器.

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;
}

这篇关于strnatcmp()PHP的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆