检测第一个中间项目的简便方法

时间:2011-12-03 11:35:23

标签: php

我的网站上有照片网格。每个项目都应该有自己的CSS。我有firstmiddlelast。我写了一个PHP-snippet,它可以解决这个问题,但是它非常有限并且非常不合适。

$firstItem = array(1,4,7,10,13,16,19,22,25,28,31,34,37,40,43,46,49);
if (in_array($key, $firstItem)) {
    echo '<div class="photoblock first">';
}
$secondItem = array(2,5,8,11,14,17,20,23,26,29,32,35,38,41,44,47,50);
if (in_array($key, $secondItem)) {
    echo '<div class="photoblock middle">';
}
$thirdItem = array(3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48);
if (in_array($key, $thirdItem)) {
    echo 'div class="photoblock last">';
}

正如你所看到的,一旦我有超过50张照片,我需要重新填充数组......有更简单的方法吗?

3 个答案:

答案 0 :(得分:4)

尝试使用(伪代码):

if ($key % 3 == 1) // Is a first item
if ($key % 3 == 2) // This as a middle item
if ($key % 3 == 0) // ...and last

A % B是模数运算符,它为你提供A除以A的其余部分。例如22%7 - &gt; 1,因为7 * 3 = 21,22 - 21 = 1。

答案 1 :(得分:2)

模数运算符(%)是你的朋友。

$positions = array('first', 'middle', 'last');    

foreach($items as $index => $item) {

    $position = $positions[$index % 3];

    echo 'div class="photoblock ' . $position . '">';

}

CodePad

答案 2 :(得分:0)

为什么不使用数学?

if ($key % 3 == 1) {
    echo '<div class="photoblock first">';
} elseif ($key % 3 == 2) {
    echo '<div class="photoblock middle">';
} elseif ($key % 3 == 0) {
    echo '<div class="photoblock last">';
}

根据php文档:

Modulus
$a % $b
Remainder of $a divided by $b

另一种想到这一点的方法是,你的第一个数组中的所有数字(1,4,7,...)都是“3的倍数加1”(0 * 3 + 1 = 1,1) * 3 + 1 = 4,2 * 3 + 1 = 7等...)。这就是“3”和“1”的情况。同样,第二组中的所有数字都是“3的倍数加2”,最后一组中的所有数字都是“3的倍数加0”。

相关问题