<?php
$classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');
if($productCatalogs != null){
$i = 0;
foreach($productCatalogs as $productCatalog){
$i++;
if($i % 2 == 0){
// if $i is even number
echo '<li class="{ use classname here }"><a href="#">Link name</a></li>';
} else {
// if $i is odd number
echo '<li><a href="#">Link name</a></li>';
}
}
}
?>正如上面的代码所示,当$classNames仅为偶数时,我希望在$i中使用每个$i值,比如第一次偶数记录使用{DURBER-2 },然后偶数记录使用{ above 4 }。
下面是我想要的代码结果,
<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-8"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-2"></li>
<li></li> // if record is odd number, doesn't need class name
<li class="margin-4"></li>
...发布于 2016-08-15 02:32:05
只需在数组中使用一个计数器变量作为索引,并在找到偶数number.Also时进行增量,如果您有许多元素,则需要检查是否到达数组的末尾,并按如下方式重置counter.Something:
<?php
$classNames = array('margin-2', 'margin-4', 'margin-2', 'margin-8');
if($productCatalogs != null){
$i = 0;
$even_counter=0;
foreach($productCatalogs as $productCatalog){
$i++;
if($i % 2 == 0){
// if $i is even number
echo '<li class="'.$classNames[$even_counter].'"><a href="#">Link name</a></li>';
//when we reach the end of the array we reset our counter to 0
$even_counter=($even_counter+1==count($classNames))?0:$even_counter+1;
} else {
// if $i is odd number
echo '<li><a href="#">Link name</a></li>';
}
}
}
?>https://stackoverflow.com/questions/38948434
复制相似问题