我有一个像这样的数组
$products_array = array('test product', 'test new product', 'test lipsum', 'test lorem', ....);
我刚刚从这样的数组中获取值
echo '<ul>';
foreach( $products_array as $product_array ) {
echo '<li>$product_array</li>';
}
echo '</ul>';
但在这里我想要一些动态的东西。我想根据用户设置的值添加类名。假设用户想要连续显示 5 个列表,那么标记将如下所示
<ul>
<li class="first">test product</li>
<li>test new product</li>
<li>test lipsum</li>
<li>test lorem</li>
<li class="last">test update</li>
<li class="first">test new product</li>
<li>test a product</li>
<li>test new lipsum</li>
<li>test lorem</li>
<li class="last">test new update</li>
</ul>
所以在这里你可以看到最后意味着在每 5 个帖子最后添加类之后,它首先将类添加到第一个列表中,并在第 5 个列表 block 之后。因此,在这种情况下,当用户设置 $class = 3 时,它将把最后一个类添加到第三个 block ,第一个类将添加到第一个 block ,列表 block 将添加到第三个、第六个、第九个等之后
我就是这样做的
$last = '4' //set 4. so for 4th,8th,12th it will add class last. and for 1st, 5th, 9th it will add class first
echo '<ul>';
$i = 0;
$count = count($products_array);
foreach( $products_array as $product_array ) {
$i++;
$class = '';
if( $i == $count ) {
$class = 'last';
}
echo '<li class='.$class.'>$product_array</li>';
}
echo '</ul>';
但它不起作用。那么有人可以告诉我该怎么做吗?任何帮助和建议都将非常感激。谢谢
最佳答案
使用模数来确定要添加的类。逻辑是...
- 当余数为 0 时,我们位于每组的最后一项(n 中的n)
- 当余数为 1 时,我们位于每组的第一项(n 中的第 1)
- 否则,我们就处于中间位置
例如
$last = 4;
?>
<ul>
<?php
foreach ($products_array as $index => $product) :
switch(($index + 1) % $last) { // array indexes are 0-based so add 1
case 0 :
$class = 'last';
break;
case 1 :
$class = 'first';
break;
default :
$class = '';
}
?>
<li class="<?= $class ?>"><?= htmlspecialchars($product) ?></li>
<?php endforeach ?>
</ul>
关于Php 动态添加类到第一个和最后一个 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32180649/