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 );

如果您不想按字母顺序排列它们,other ways 可以做到。