删除逗号从最后一个项目类别列表- wordpress


Remove comma from last item category list – wordpress

使用

<?php
    foreach((get_the_category()) as $category) {
        echo $category->cat_name . ', ';
    }
?>

现在,这显然在每个"类别"的末尾输出一个逗号,我该如何从列表的最后一项中删除逗号呢?

使用rtrim:

$cats = '';
foreach((get_the_category()) as $category) {
    $cats .= $category->cat_name . ', ';
}
echo rtrim($cats, ', ');

这里有另一种方法,使用join函数-

echo join(",",array_map(function($category){return $category->cat_name;}, get_the_category()));

你可以试试:

$categories = array();
foreach(get_the_category() as $category) {
    $categories[] = $category->cat_name;
}
echo implode($categories, ',');