2013-04-15 43 views
-1

我正在寻找一种方法来做一些稍微复杂的第n个记录评审,类似于PHP中的jQuery/CSS3 nth-child(3n-1),所以每行有三个cols,中间一个需要“mid”类,添加。我最好不要使用jQuery,因为从页面加载和正在添加的类似乎总是存在延迟。PHP第n个记录

所以像下面的东西,但我知道这将意味着$zxc % 2,但我们都开始在某个地方。

<?php $zxc = 1; ?> 
<?php foreach($products as $product): ?> 
<div class="theProductListItem<?php if($zxc % (3-1) == 0){?> mid<?php } ?>"> 
<!--product contents--> 
</div> 
<?php $zxc++; ?> 
<?php endforeach; ?> 
+0

为什么不只是如果($ i == 3){$ i = 1; }那么你总是可以检查$ i是3还是什么,它总是第三个记录 –

+0

为什么不使用CSS3'n-child()'? – Spudley

+0

嗨。我不想要第三张唱片,我正在寻找第3-1张唱片,或者5-2张唱片,或者其他类似的东西。 – ggdx

回答

3

使用此:

if(($zxc % 3) == 1) 
+0

他正在寻找2,5,8 ...。我没有看到你的工作。 – Alvaro

+1

完美。谢谢hjpotter92,如果(($ zxc%3)== 2)做到了。 – ggdx

+0

@Steve **中间一个需要有班级** – hjpotter92

0

您需要使用% 3通过定义你想 '每3个项目'。

然后你有一些选择,你可以开始你的变量在一个偏移量。 例如

$x = 2; 
foreach ($array as $item) { 
    ... 
    if ($x % 3 == 0) { 
     ... 
    } 
    ... 
} 

你也可以从更常见的0或1开始,并改变你的比较。

$x = 0; 
foreach ($array as $item) { 
    ... 
    if ($x % 3 == 1) { 
     ... 
    } 
    ... 
} 

从表面上看,您可以将最后一个示例更改为此。

$x = 0; 
foreach ($array as $item) { 
    ... 
    if (($x % 3) - 1 == 0) { 
     ... 
    } 
    ... 
} 
0

这是一种完成你想要的而不必担心模量计算的方法,虽然被授予,但它有点冗长。它扩展了标准ArrayIterator用一些方法来跳过记录:

class NthArrayItemIterator extends ArrayIterator 
{ 
    private $step; 
    private $offset; 

    public function __construct($array, $step = 1, $offset = 0) 
    { 
     parent::__construct($array); 
     $this->step = $step; 
     $this->offset = $offset; 
    } 

    private function skipn($n) 
    { 
     echo "skipn($n)\n"; 
     while ($n-- && $this->valid()) { 
      parent::next(); 
     } 
    } 

    public function rewind() 
    { 
     parent::rewind(); 
     $this->skipn($this->offset); 
    } 

    public function next() 
    { 
     $this->skipn($this->step); 
    } 
} 

foreach (new NthArrayItemIterator(array(1, 2, 3, 4, 5, 6), 3, 2) as $item) { 
    echo "$item<br />"; 
} 

Demo

它在这种情况下输出第三和第六项。