2017-10-18 117 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) 
     ) 
    ) 

)); ?> 

有沒有辦法實現這個?謝謝!

+0

'$ termoutput = [];'在foreach之前。然後在循環中使用'$ termoutput [] = $ term-> slug;'......這就是字面意思。 – naththedeveloper

回答

2

你應該積累的輸出轉換成一個這樣的數組:

$termoutput = array(); 

... 

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

然後,在代碼的第二部分:

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

完美。對我來說工作得很好。謝謝! – Filip

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

    ));  
?> 

這將存儲$條款而─>蛞蝓$ termoutput []爲一個數組。

+0

這會在某些情況下發出警告,因爲您尚未在循環之前將'$ termoutput'預設爲數組。在foreach之前添加'$ termoutput = array();'。 – naththedeveloper

+1

@ naththedeveloper對不起,忘記了,正忙着編輯他的代碼。謝謝 – hungrykoala