2010-08-10 32 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