2013-12-11 47 views
0

我正在打擊PHP thingy。我的代碼輸出正確,但最後會留下不需要的逗號。有沒有辦法得到(或顯示)最後一個逗號?任何提示表示讚賞。php輸出中不需要的逗號

<?php echo mtbxr_val('dog_name'); ?> 
&nbsp;is&nbsp; 
<?php 
$terms = get_the_terms($post->ID , 'behaviour_options'); 
foreach ($terms as $term) { 
    echo mb_strtolower($term->name); 
    echo ", "; 
} 
?> 

回答

0

我喜歡用數組來收集值更簡單的方法然後用join()回顯。例如:

<?php 
$terms = get_the_terms($post->ID , 'behaviour_options'); 
$names = array(); 
foreach ($terms as $term) { 
    $names[] = mb_strtolower($term->name); 
} 
echo join(', ', $names); 
?> 
+0

謝謝!這有助於......我非常感激。 – Gerard

3

我通常存儲在數組中,並使用implode()

foreach ($terms as $term) { 
    $output[] = mb_strtolower($term->name); 
} 
echo implode(', ', $output); 
0

這將是做

<?php 
    $terms = get_the_terms($post->ID , 'behaviour_options'); 
    $out = array(); 
    foreach ($terms as &$term) { 
     $out[] = mb_strtolower($term->name); 
    } 

    echo implode(", ",$out); 
?> 
+0

忽略此評論 –

+1

除了'$ terms'是對象的數組,因此環和參考'$項 - > name'。 – AbraCadaver

+0

我剛纔看到了,我的錯誤。編輯回覆 –

0

除了破滅,你也可以使用一個計數器:

<?php 
$terms = get_the_terms($post->ID , 'behaviour_options'); 
$termCount = count($terms); 
foreach ($terms as $term) { 
    echo mb_strtolower($term->name); 
    if (--$termCount) echo ", "; 
} 
?>