Ami*_*min 1 php math loops series
我需要$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>';
}
Run Code Online (Sandbox Code Playgroud)
最后我需要输出这样的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>
Run Code Online (Sandbox Code Playgroud)
通用方法:
$pattern = [ 1, 2, 2, 1 ]; // or array( 1, 2, 2, 1 ); for PHP < 5.4
$idx = 0;
while ( expression ) {
$number = $pattern[ $idx ++ % count( $pattern ) ];
}
Run Code Online (Sandbox Code Playgroud)