我的应用程序中有一个foreach
声明,它与我的数据库结果列表相呼应:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
我想:
在每三个结果中,给 div 一个不同的类。我怎样才能做到这一点?
您可以使用计数器和模/模运算符,如下所示:
<?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 ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
如果$featured_projects
数组基于增量索引,您可以简单地使用索引和模%
运算符。
否则,您将不得不添加一个计数器。
在此循环中添加一个计数器并检查计数器是否等于 3 并应用类。
使用计数器和模运算符,这很容易实现
这是工作版本,对不起我的上一个版本:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
产生:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>
您可以在循环中添加一个计数器...尝试以下操作...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
使您的代码大部分保持不变的是
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
但是您可能需要考虑在“each($featured_projects)”周围使用 for 或 while 构造(请参阅http://php.net/manual/en/function.each.php),这可能会产生更简洁的代码。
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>