Foreach 和第 n 个术语

Foreach and nth terms

我正在尝试将内容打印到三列中,这意味着对于第一列,我需要检索与术语 3n-2 匹配的记录。我该怎么做......也许使用模数?谢谢!

foreach($grid as $tile):
    echo '<div class="tile"><img src="/media/full/' . $tile['source'] . '"/></div>';
endforeach;

我想你要找的只是一个额外的计数器:

$i=0;
foreach($grid as $tile) {
    if($i++ % 3 == 0) {
        //do something every 3rd time
    }
    //do something every time
}

是的,我会使用模 php 运算符 %,如果我正确理解你的意思的话:

<?php
  $grid = array(1,2,3,4,5,6,7); # just for testing

  $n = 1;
  foreach($grid as $tile) {
    if (($n + 2) % 3 == 0) {
      #echo '<div class="tile"><img src="/media/full/' . $tile['source'] . '"/></div>';
      echo "$n\n"; # just for testing
    }
    $n++;
  }
?>

产生:

$ php x.php 
1
4
7

foreach 也可以为您提供索引,就像您已经建议的那样,您可以使用 IF 选择您想要的行,或者您可以执行负 IF 并使用 continue; 跳过您不想要的内容。

foreach($grid as $i => $tile):
    if ($i % 3 == 2):

我想你在找这样的东西:

(示例代码,只需将$arr更改为$grid

<?php

    $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

    for($count = 0; $count < count($arr); $count++) {

        if($count % 3 == 0 && $count != 0)
            echo "<br />";
        echo    $arr[$count];

    }


?>

输出:

123
456
789

或者如果您想要单独数组中的列:

<?php

    $arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
    $columnOne = array();
    $columnTwo = array();
    $columnThree = array();

    for($count = 0; $count < count($arr); $count++) {

        if($count % 3 == 0)
            $columnOne[] = $arr[$count];
        elseif($count % 3 == 1)
            $columnTwo[] = $arr[$count];
        else
            $columnThree[] = $arr[$count];

    }

    print_r($columnOne);
    print_r($columnTwo);
    print_r($columnThree);

?>

输出:

Array ( [0] => 1 [1] => 4 [2] => 7 )
Array ( [0] => 2 [1] => 5 [2] => 8 )
Array ( [0] => 3 [1] => 6 [2] => 9 )