2010-08-10 104 views
0

这里是一个例子我的WordPress的帖子。我想添加一些类最后的我希望能像<li>PHP:如何添加奇数/偶数循环到我的无序列表

<li class='lastli'>

<ul class="tabs"> 
<?php 
    global $post; 
    $myposts = get_posts('numberposts=3'); 
    foreach($myposts as $post) : 
    setup_postdata($post); 
    ?> 
<li><a href="#"><?php the_title(); ?></a></li> 
<?php endforeach; ?>   
</ul> 

结果:

<ul> 
<li>Title 1</li> 
<li>Title 1</li> 
<li class='lastli'>Title 1</li> 
<ul> 

任何最后的无序列表会是<li class='lastli'>。让我知道该怎么做?

回答

3

使用一个for循环

<ul class="tabs"> 
<?php 
    global $post; 
    $myposts = get_posts('numberposts=3'); 
    $nposts = count($myposts); 
    for($i=0;$i<$nposts;$i++): 
    $post = $myposts[$i]; 
    setup_postdata($post); 
    ?> 
<li<?php if ($i==$nposts-1):?> class='lastli'<?php endif;?>><a href="#"><?php the_title(); ?></a></li> 
<?php endfor; ?>   
</ul> 

注:在循环之前计算的数组大小是很好的做法,否则PHP会在每一轮循环

+0

谢谢本10!真正的超级修复。 ':?> class'需要有一个空格。 – kampit 2010-08-10 03:21:14

+0

好点。固定 – Ben 2010-08-10 03:23:56

0
<ul class="tabs"> 
<?php 
    global $post; 
    $myposts = get_posts('numberposts=3'); 
    $i = 0; 
    for ($i = 0; $i < count($myposts); $i++) { 
    $post = $myposts[$i]; 
    setup_postdata($post); 
    ?> 
<li <?= ($i==count($myposts)-1)?"class='lastli'":"" ?>><a href="#"><?php the_title(); ?></a></li> 
<?php } ?>   
</ul> 
1
<ul class="tabs"> 
<?php 
    global $post; 
    $myposts = get_posts('numberposts=3'); 
    $nposts = count($myposts); 
    $odd_even_class = array('odd_class', 'even_class'); 

    for($i=0;$i<$nposts-1;$i++): 
    $post = $myposts[$i]; 
    setup_postdata($post); 
    ?> 
<li <?php echo $odd_even_class[($i+1)%2];?>><a href="#"><?php the_title(); ?></a></li> 
<?php 
endfor; 
$post = $myposts[$i]; 
setup_postdata($post); 

<li class='lastli'><a href="#"><?php the_title();?></a></li>   
</ul> 
的评价它

您不需要条件声明:)

+0

我不确定数组查找是否比条件测试更快:)另外,您可能不需要$ curr_class,您可以使用$ i%2作为索引..并且数组应该可能是数组('even_class','odd_class') – Ben 2010-08-10 23:42:09

+0

我制作了奇数/偶数类选择技术。我已经说过 - “你不需要条件语句:)”,因为你最后一行的选择条件,至少我已经避免了那个容易:)。不是奇数/偶数。 – Sadat 2010-08-11 05:09:41