简单的方法来检测第一,中间,最后项目


Easy way to detect first-middle-last item

我有一个网站的照片网格。每个项目都应该有自己的css。我有first middlelast。我写了一个php代码片段来实现这个功能,但它非常有限,而且对规模非常不友好。

$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张图片,我需要重新填充数组…有更简单的方法吗?

Try something as(伪代码):

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除以b的剩余部分,例如22 % 7 -> 1,因为7 * 3 = 21,22 - 21 = 1。

模数运算符(%)在这里是您的朋友。

$positions = array('first', 'middle', 'last');    
foreach($items as $index => $item) {
    $position = $positions[$index % 3];
    echo 'div class="photoblock ' . $position . '">';
}

CodePad .

为什么不直接用数学呢?

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"answers"1"出现的地方。同样,第二组中的所有数字都是"3 + 2的倍数",最后一组中的所有数字都是"3 + 0的倍数"。