如何在php中的foreach语句的每第三个结果上输出一个值?

hai*_*ets 10 php foreach echo

foreach在我的应用程序中有一条声明回显了我的数据库结果列表:

<?php

foreach($featured_projects as $fp) {
  echo '<div class="result">';
  echo $fp['project_name'];
  echo '</div>';
}

?>
Run Code Online (Sandbox Code Playgroud)

我想要:

在每第三个结果上,给div一个不同的类.我怎样才能做到这一点?

Tre*_*non 19

您可以使用计数器和模/模数运算符,如下所示:

<?php

// control variable
$counter = 0;

foreach($featured_projects as $fp) {

    // reset the variable
    $class = '';

    // on every third result, set the variable value
    if(++$counter % 3 === 0) {
        $class = ' third';
    }

    // your code with the variable that holds the desirable CSS class name
    echo '<div class="result' . $class . '">';
    echo $fp['project_name'];
    echo '</div>';
}

?>
Run Code Online (Sandbox Code Playgroud)


ab_*_*v86 6

<?php

foreach ($featured_projects as $i => $fp) {
    echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
    echo $fp['project_name'];
    echo '</div>';
}
?>
Run Code Online (Sandbox Code Playgroud)