2010-05-24 42 views
2

我有兩個爲每個循環和我試圖輸出不同的是每個第二個結果不同:ForEach循環:每月的第二個結果的不同輸出的東西

foreach ($wppost as $wp) { 
      $wp_title = $wp->post_title; 
      $wp_date = strtotime($wp->post_date); 
      $wp_slug = $wp->post_name; 
      $wp_id = $wp->ID; 
      // Start Permalink Template 
      $wp_showurl = $wp_url; 
      $wp_showurl = str_replace("%year%", date('Y', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%monthnum%", date('m', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%day%", date('d', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%hour%", date('H', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%minute%", date('i', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%second%", date('s', $wp_date), $wp_showurl); 
      $wp_showurl = str_replace("%postname%", $wp_slug, $wp_showurl); 
      $wp_showurl = str_replace("%post_id%", $wp_id, $wp_showurl); 
      // Stop Permalink Template 
      $wp_posturl = $blog_address . $wp_showurl; 
      echo '<li><a href="'.$wp_posturl.'" title="'.$wp_title.'">'.$wp_title.'</a></li>';   
     } 

對於這一個我希望它呼應<li class="even">,而不是隻需<li>爲每個第二個結果。我認爲這將不得不改變爲一個for循環來完成這一點,但我不知道如何做到這一點沒有打破它。

完全一樣的這一個:

if(is_array($commenters)) { 
     foreach ($commenters as $k) { 
     ?><li><?php 
      if($ns_options["make_links"] == 1) { 
      $url = ns_get_user_url($k->poster_id); 
      if(trim($url) != '') 
      { 
       echo "<a href='" . $url . "'>"; 
      } 
      } 
      if($ns_options["make_links"] == 2) { 
      $url = ns_get_user_profile($k->poster_id); 
      echo "<a href='" . $url . "'>"; 
      } 


      $name = $bbdb->get_var(" 
     SELECT user_login 
     FROM $bbdb->users 
     WHERE ID = $k->poster_id"); 
     echo ns_substr_ellipse($name, $ns_options["name_limit"]); 

      if(trim($url) != '' && $ns_options["make_links"] == 1) { 
      echo "</a>"; 
      } 
      if($ns_options["make_links"] == 2) { 
      echo "</a>"; 
      } 
      if ($ns_options["show_posts"] == 1) 
      { 
      echo " (" . $k->num_posts . ")\n"; 
      } 
      echo $ns_options["end_html"] . "\n"; 
      unset($url); 
     } 
    } else { 
     ?></li><?php 
    } 

感謝,

韋德

回答

5

您可以創建一個「計數」變量,然後使用$count % 2結果,以確定它是否是一個奇數或偶數行:

$rowCount = 0; 
foreach ($wppost as $wp) { 
    // stripping stuff: 
    echo '<li'; 
    // increase $rowCount - if the remainder of a division by 2 is 1, echo extra class info: 
    if ($rowCount++ % 2 == 1) echo ' class="even"'; 
    echo '><a href="'.$wp_posturl.'" title="'.$wp_title.'">'.$wp_title.'</a></li>';   
} 


if(is_array($commenters)) { 
    $commentCount = 0; 
    foreach ($commenters as $k) { 
    ?><li<?php echo ($commentCount++%2==1)?' class="even"':''?>><?php 
    //stripped the rest of the loop: 
    } 
} 
+0

完美,謝謝! – 2010-05-24 23:00:41

相關問題