PHP While和For循环分组(使用WP ACF)


PHP While and For Loop Grouping (using WP ACF)

使用'while'语句进行循环,我得到以下输出:

move_it
clean_beauty
on_our_radar
move_it

我想输出这些字段(对于$featured_type)是相同的。如。我想输出如下内容:

move_it
move_it
clean_beauty
on_our_radar

下面是我当前用基本循环输出的第一个示例。我循环通过字段(从一个高级自定义字段重复器在WordPress)。

        while( has_sub_field( 'featured_posts', $acf_id )  ):

        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );
        echo $featured_type . '<br />';
        endwhile;

我已经写了一些代码,但知道必须有一个更优雅的方式来实现相同的结果。我的方式很笨拙!任何建议感谢。

        <?php 
        while( has_sub_field( 'featured_posts', $acf_id )  ):

        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );

        if ($featured_type == 'move_it') {
            echo  $featured_type . '<br />';
        }
        endwhile;
        while( has_sub_field( 'featured_posts', $acf_id )  ):

        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );

        if ($featured_type == 'clean_beauty') {
            echo $featured_type .  '<br />';
        }
        endwhile;
        while( has_sub_field( 'featured_posts', $acf_id )  ):

        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );

        if ($featured_type == 'on_our_radar') {
            echo  $featured_type .  '<br />';
        }
     endwhile; ?>

使用数组可以存储值,然后排序,最后回显它们:

$featured_types = array();
while( has_sub_field( 'featured_posts', $acf_id )  ):
    $featured_post = get_sub_field( 'featured_post', $acf_id );
    $featured_type = get_field( 'editorial_template', $featured_post->ID );
    $featured_types[] = $featured_type;
endwhile;
sort( $featured_types );
echo implode( '<br>', $featured_types );

如果您不想按字母顺序排列,还有其他方法。