2017-10-18 4 views
0

分類法の用語リストを取得するループがあります。ループ出力を変数に保存する

<?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 []$ TERM->スラグを格納します

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

    ));  
?> 

+0

'$ termoutput = [];' foreachの前に。 echoの代わりにループ内で '$ termoutput [] = $ term-> slug;' ...それは文字通りです。 – naththedeveloper

答えて

2

あなたはこのような配列にあなたの出力を蓄積する必要があります。

$termoutput = array(); 

... 

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

次に、あなたのコードの2番目のセクションで:

... 
'terms' => $termoutput 
+0

パーフェクト。私のためにうまく動作します。ありがとうございました! – Filip

2

はこれを試してみてください。

+0

ループの前に配列として '$ termoutput'を設定していないため、警告が表示されることがあります。 foreachの前に '$ termoutput = array();'を追加してください。 – naththedeveloper

+1

@naththedeveloper申し訳ありませんが、彼のコードを編集中です。ありがとうございます – hungrykoala

関連する問題