A comma issue with foreach

2019-09-13 04:20发布

问题:

I have this code. This code is used to display all categories in WordPress.

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

But even when there's just 1 category showing, the comma behind it is still there. I want it like this:

  • 1 category: [category]
  • 2 categories: [category], [category]
  • And same goes for 3 categories: [category], [category], [category]

Is this possible? I have tried:

foreach((get_the_category()) as $category) {
    $getcount = count(get_the_category());
    if($getcount > 1) {
        echo $category->cat_name . ', ';
    } else {
        echo $category->cat_name;
    }
}

But that's also not the best solution and when there's more than 1 category, the same issue will accur.

Help is much appreciated.

回答1:

You could use implode()

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


回答2:

why don't you use the_category(', ');? It will also list all post categories



回答3:

You could use implode:

$categories = []
foreach((get_the_category()) as $category) {
    $categories[] = $category->cat_name;
}

echo implode(', ', $categories);

Or you may use implode with array_map:

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


回答4:

try using this.

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


回答5:

The easiest way is simply to use implodeafter building up an array of Category Names within your foreach Loop. And it takes just a few lines like so:

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


标签: php wordpress