【问题标题】:Save loop output into a variable将循环输出保存到变量中
【发布时间】:2017-10-18 20:15:55
【问题描述】:

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

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

) );    ?>

有没有办法做到这一点?谢谢!

【问题讨论】:

  • $termoutput = []; 在 foreach 之前。然后在你的循环中而不是 echo 使用 $termoutput[] = $term-&gt;slug;... 就是字面意思。

标签: php wordpress advanced-custom-fields


【解决方案1】:

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

$termoutput = array();

...

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

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

...
'terms' => $termoutput

【讨论】:

  • 完美。对我来说很好。谢谢!
【解决方案2】:

试试这个:

 <?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 预设为数组。在 foreach 之前添加$termoutput = array();
  • @naththedeveloper 抱歉忘记了,正忙着编辑他的代码。谢谢