将循环输出保存到变量中

Save loop output into a variable

我有一个循环来获取分类法的术语列表。

    <?php 
  $terms = get_field('modell');
  if( $terms ):
    $total = count($terms);
    $count = 1;
    foreach( $terms as $term ):
      ?>
      '<?php echo $term->slug; ?>'
      <?php 
      if ($count < $total) {
        echo ', ';
      }
      $count++;
    endforeach;
  endif; 
?>

循环输出是这样的:

 'termname-one','termname-two','termname-three' 

现在我想将此输出保存到变量 ($termoutput) 并将其插入到以下循环的术语数组中:

<?php 
query_posts( array(  
    'post_type' => 'posttypename', 
    'posts_per_page' => -1, 
    'orderby' => 'title',
    'order' => 'ASC',
    'tax_query' => array( 
       array( 
          'taxonomy' => 'systems', 
          'field' => 'slug', 
         'terms' => array($termoutput)
       ) 
   ) 

) );    ?>

有办法实现吗?谢谢!

试试这个:

 <?php 
  $terms = get_field('modell');
  if( $terms ):
    $total = count($terms);
    $count = 1;
    $termoutput = array();
    foreach( $terms as $term ):

      echo "'".$term->slug."'"; 
      $termoutput[] = $term->slug;

      if ($count < $total) {
        echo ', ';
      }
      $count++;
    endforeach;
  endif; 
?>


<?php 
    query_posts( array(  
        'post_type' => 'posttypename', 
        'posts_per_page' => -1, 
        'orderby' => 'title',
        'order' => 'ASC',
        'tax_query' => array( 
          array( 
              'taxonomy' => 'systems', 
              'field' => 'slug', 
             'terms' => $termoutput
           ) 
       ) 

    ) );    
 ?>

这会将 $term->slug 作为数组存储到 $termoutput[]

您应该将输出累积到这样的数组中:

$termoutput = array();

...

foreach( $terms as $term ) {
    $termoutput[] = $term->slug;
}

然后,在您的代码的第二部分:

...
'terms' => $termoutput