如果最后一个元素echo'class="last"'


if last element echo'class="last"'

我是php的新手,我试图创建一个简单的代码,在"while"循环的最后一个元素的开始打印一个"最后"类。循环中只有两个项目(博客摘录),因此我在下面尝试使用if ($ I == 1)…谢谢你的帮助。

下面是我到目前为止的代码-它只返回p
   <?php
     $i = 0;
     if($i == 1) {
      echo '<p class="last">';
     }
     else {
      echo '<p>';
     }
   ?>
编辑:

感谢到目前为止的帮助。非常感谢-我在下面提供了更多的信息(我在深夜发布,所以我意识到我还没有那么清楚)。

这是我想写的完整代码。它正在从Wordpress中提取博客摘录-目前限制为2篇博客文章。

<?php 
 $posts = new WP_Query('showposts=2');
 while ( $posts->have_posts() ) : $posts->the_post(); 
?>
 <p><a href="<?php echo get_permalink(); ?>"><?php echo the_title(); ?></a><br/>
    <?php echo substr(get_the_excerpt(), 0,200); ?>... <a href="<?php echo get_permalink();   ?>">Read More</a></p>
<?php endwhile; ?> 
<?php wp_reset_query(); ?> 

我想在第5行开始的p中添加类"last"-除了最后一个博客。

再次感谢。

Nick的回答几乎说明了所有需要说的。我唯一要做的就是稍微修改一下,以避免重复,特别是如果段落标签的内容比较复杂的话。

在Nick的代码中做以下调整可能会更好:

<style>
  #contents p:last-child {
     PUT CONTENTS OF CLASS HERE
  }
</style>
<body>
  <div id="#contents">
<?php
  $numLoops = 2;
  $ctext=""
  for($i=0; $i<$numLoops; $i++) {
    $info="whatever";
    if($i == (numLoops-1)) {
        $ctext=' class="last"';
    }
    echo "<p${ctext}>${info}</p>'n";
  }
?>
  </div>
</body>

欢呼

所以你有两个段落,你想应用类"last"到最后一个?听起来这个问题最好用CSS

来处理。
<style>
  #contents p:last-child {
     PUT CONTENTS OF CLASS HERE
  }
</style>
<body>
  <div id="#contents">
    <p> first info</p>
    <p> last info </p>
  </div>
</body>

OR如果你想了解循环

<?php
  $numLoops = 2;
  for($i=0; $i<$numLoops; $i++) {
    if($i == (numLoops-1)) {
        echo '<p class="last">';
     } else {
        echo '<p>';
     }
  }

我们在for循环中所做的是首先设置变量$i=0;然后设置一个测试,只要变量小于我们想要的循环次数,就继续循环。接下来,我们设置每个循环要做什么,在本例中,我们每次将变量增加1。

第一次循环

i=0, we see that 0 is < 2 so we continue
第二循环

We execute the $i++ so we increment $i by 1 from 0 to $i=1, 
we test and see $i=1 is still less than 2 so we continue.

第三次尝试循环

We increment $i by 1 and get $i=2.  
We test to see if this is less than 2, but it is NOT so we do not execute code in the loop

主要问题是你的代码中没有循环,如果你有,你没有增加变量$i