while循环将类添加到第一个结果

时间:2012-03-30 16:14:39

标签: php

我有以下

while ( $query->have_posts() )
{
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
    echo "<div class='clearfix card-prod ".($i==0?'first':'')."'><div class='top-dets'><span class='card-title'>";
    echo the_title();
    echo "</span>";


// Network query 
    $network_value = get_post_custom_values('srchnetwork');
    foreach ( $network_value as $key => $value ) {
    echo '<span class="srch-val-">'. $value . '</span>'; }

// Pricing Query
    $pricing_value = get_post_custom_values('srchpricing');
    foreach ( $pricing_value as $key => $value ) {
    echo '<span class="srch-val-1">'. $value . '</span>'; }

// Setup Query
    $setup_value = get_post_custom_values('srchsetupfee');
    foreach ( $setup_value as $key => $value ) {
    echo '<span class="srch-val-2">'. $value . '</span>'; }

// Services Query
    $services_value = get_post_custom_values('srchservices');
    foreach ( $services_value as $key => $value ) {
    echo '<span class="srch-val-3">'. $value . '</span></div>'; }

// Big Card Query
    $bigcard_value = get_post_custom_values('bigcard');
    foreach ( $bigcard_value as $key => $value ) {
    echo '<img src="wp-content/themes/cafc/images/cards/'. $value . '" />'; }


//      echo '<img src="wp-content/themes/cafc/images/top-choice.jpg" alt="Top Choice" class="topchoice">';

    echo the_excerpt()."</div>";   }};
} 

我想知道是否可以将第一个返回的结果包装在span标签中?如果是这样我怎么去做呢?谢谢

4 个答案:

答案 0 :(得分:3)

作为一种通用方法,只要您需要行为只在第一次通过循环执行时,您只需使用标志变量来检查是否执行该行为。

$firstLoop = true;
while( $query->have_posts() ){

    //do some things

    if( $firstLoop ){
        //do things on only the first loop
    }

    //do other things

    $firstLoop = false;
}

或者,对于foreach循环:

$firstLoop = true;
foreach( $network_value as $key => $value ){

    if( $firstLoop ){
        //do things on only the first loop
    }

    //do other things

    $firstLoop = false;
}

这避免了需要计算循环,并且它适用于任何循环结构。只需记住在循环结束时始终将标志变量设置为false。

答案 1 :(得分:2)

$i = -1;
while ( $query->have_posts() )
{
$i++;
$query->the_post();
if ( $keys = get_post_custom_keys() )
{
echo "<div class='clearfix card-prod ".($i?'first':'')."'><div class='top-dets'><span class='card-title'>";
echo the_title();
echo "</span>";
...

检查此行( $i ? 'first' : '')

答案 2 :(得分:0)

在此基础上我的假设会在每个循环周围产生类似的结果......

// Network query
$neti = 1;
$network_value = get_post_custom_values ( 'srchnetwork' );
foreach ( $network_value as $key => $value ) {
  if($neti == 1){
      echo '<span class="srch-val-">' . $value . '</span>';
  }else{
      echo $value;
  }
  $neti++;
}

答案 3 :(得分:0)

您可以从柜台寻求帮助:

$count  = 0;
while(){
  <div class="<?php $count++; if($count == 1) { echo ' active'; } ?>">hello</div>
}