如何在 php 中创建“122112211221”系列

How to create a "122112211221" series in php

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

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>

通用方法:

$pattern = [ 1, 2, 2, 1 ];   // or array( 1, 2, 2, 1 ); for PHP < 5.4
$idx = 0;

while ( expression ) {
    $number = $pattern[ $idx ++ % count( $pattern ) ];
}

有一个 $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++;    
    }
}

?>