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

问题描述 投票:0回答:4

我有以下内容

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标签中?如果是这样我怎么去做呢?谢谢

php
4个回答
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' : '')


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。


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++;
}

0
投票

你可以从柜台获得帮助:

$count  = 0;
while(){
  <div class="<?php $count++; if($count == 1) { echo ' active'; } ?>">hello</div>
}
© www.soinside.com 2019 - 2024. All rights reserved.