【问题标题】:How to create a "122112211221" series in php如何在php中创建“122112211221”系列
【发布时间】:2016-02-01 18:15:30
【问题描述】:

我需要在我的循环中使用$counter 来返回这样的系列:

1 2 2 1 1 2 2 1

遗憾的是,我的数学不太好,无论我尝试什么都遇到了死胡同。 这是我尝试的最后一件事。

$counter = 0;

while( statement ) {
    ++$counter;

    // Making sure the second element is loaded
    if( $counter > 2 )
        $twoloaded = true;

    if( $counter >= 2 )
        --$counter;

    echo '<article class="post post-style-' . $counter . '"> ....... </article>';
}

最后我需要输出这样的 HTML:

<article class="post post-style-1">
    ...
</article>

<article class="post post-style-2">
    ...
</article>

<article class="post post-style-2">
    ...
</article>

<article class="post post-style-1">
    ...
</article>

<article class="post post-style-1">
    ...
</article>

<article class="post post-style-2">
    ...
</article>

【问题讨论】:

    标签: php loops math series


    【解决方案1】:

    通用方法:

    $pattern = [ 1, 2, 2, 1 ];   // or array( 1, 2, 2, 1 ); for PHP < 5.4
    $idx = 0;
    
    while ( expression ) {
        $number = $pattern[ $idx ++ % count( $pattern ) ];
    }
    

    【讨论】:

    • 我不确定 $pattern = [ 1, 2, 2, 1 ]; 是否有效 php - 也许是 $pattern = array(1,2,2,1);
    • @Omnimusha 那是 PHP 5.4+;他们大约 7 岁 ;-)
    • Gotcha.. 还不如为像我这样在 xxamp 上使用较低版本的人添加替代语法。否则代码执行得很漂亮+1(2211221)
    • 好吧,可以 - 顺便说一句,我正在运行 Debian stable,它附带 5.6。
    • 很多 chagin - 仍在运行 PHP 5.3.2 :(
    【解决方案2】:

    拥有一个 $repeated 变量怎么样。您可以在切换之前使用它来检查 1 或 2 是否重复。

    <?php
    
    $counter = 1;
    $repeated = 1;
    
    while(true) {
    
        print '<article class="post post-style-' . $counter . '"> ....... </article>' . "\n";
    
        if($repeated == 2) {
    
            if($counter < 2) {
    
                $counter++;
            }
            else if ($counter == 2) {
    
                $counter--;
            }
    
            $repeated = 1;  
        }
        else {
    
            $repeated++;    
        }
    }
    
    ?>
    

    【讨论】:

    • 感谢您的宝贵时间,但代码开头缺少,它返回一个 11221 系列,它必须是 12211221
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 2015-10-02
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多