如何在PHP的每一个foreach语句的每一个结果输出一个值? [英] How to output a value on every third result of a foreach statement in php?

查看:136
本文介绍了如何在PHP的每一个foreach语句的每一个结果输出一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中有一个 foreach 语句,它回显了我的数据库结果列表:

 <?php 

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

?>



我想:



每第三个结果,给这个div一个不同的类。我可以使用一个计数器和 /manual/en/language.operators.arithmetic.php> modulo / modulus 运算符:

  <?php 

//控制变量
$ counter = 0;

foreach($ featured_projects as $ fp){

//重置变量
$ class ='';

//对于每个第三个结果,设置变量值
if(++ $ counter%3 === 0){
$ class ='third';
}

//你的代码和保存所需CSS类名的变量
echo'< div class =result'。$ class。'>' ;
echo $ fp ['project_name'];
echo'< / div>';
}

?>


I have a foreach statement in my app that echos a list of my database results:

<?php

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

?>

I would like to:

On every third result, give the div a different class. How can I achieve this?

解决方案

You can use a counter and the modulo/modulus operator as per below:

<?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>';
}

?>

这篇关于如何在PHP的每一个foreach语句的每一个结果输出一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆