我需要在循环中使用一个$counter
,它返回如下系列:
12 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++;
}
}
?>