PHP循环 - 在更改年份时重新启动序列

时间:2017-07-31 05:48:26

标签: php wordpress while-loop

我需要有关在更改年份重新启动序列的帮助,是否可能?我在WordPress中使用WP_Query,现在这是我的代码输出:

2016
1 - red - Left
2 - blue - Right
3 - blue - Left
2015
4 - red - Right //(must be 4 - red - Left) Again
5 - red - Left //(must be 5 - blue - Right)
6 - blue - Right //(must be 6 - blue - Left)
7 - blue - Left //(must be 7 - red - Right)
2014
8 - red - Right //(must be 8 - red - Left) Again

交替必须是红色 - 左蓝色 - 右蓝色 - 左红色 - 右红色 - 左,然后在一年后重置

这就是我试过的......

$current_user_id = get_current_user_ID();
$date = get_post_meta( get_the_ID(), 'date_travelled', true );
$date_travel = array($date);
$args = array(
    'post_type' => 'travel-history',
    'meta_key' => 'date_travelled',
    'orderby' => 'meta_value',
    'order' => 'DESC',
    'author' => $current_user_id
    );
    $the_query = new WP_Query( $args );

    $counter = 1;
    $year = ''; 
    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();                        

            $date_travelled = get_post_meta( get_the_ID(), 'date_travelled', true );
            $country_travelled = get_post_meta( get_the_ID(), 'country_travelled', true );
            $activity = get_post_meta( get_the_ID(), 'activity', true );
            $memory = get_post_meta( get_the_ID(), 'memory', true );
            $content = get_the_content();
            $month_travelled = date('F', strtotime($date_travelled));
            $year_travelled = date('Y', strtotime($date_travelled));                    
            ?>
               <div class="clear year no-repeat">
            <?php 
                if ($year_travelled != $year){
                    echo $year_travelled;
                    $year = $year_travelled;
                }


            ?>
            </div>
            <?php
            if ($year_travelled){

                if ($counter & 1) {
                    if ($counter % 4 == 1){
                        $color = 'red';
                    }else{
                        $color = 'blue';
                    } 
                } else { 
                    if ($counter % 4 == 0){
                        $color = 'red';
                    }else{ 
                        $color = 'blue';
                    }
                }
                if($counter & 1) {
                    echo $counter .' - '. $color. ' - Left';
                } else {
                    echo $counter .' - '. $color. ' - Right';
                }

            }

            $counter++;
                endwhile;
            endif;

有没有人可以帮助我实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:2)

听起来你需要在年度变化时重新启动序列,这应该只是

        if ($year_travelled != $year){
            echo $year_travelled;
            $year = $year_travelled;
            $counter = 1;
        }