2015-05-14 52 views
0

使用 '而' statment我得到下面的輸出循環:PHP while和for循環分組(使用WP ACF)

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

回答

2

使用數組,你可以存儲的值,然後才能最後呼應他們:

$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做到這一點。