PHP 变量在 foreach 循环中被最后一项覆盖

PHP variable gets overwritten in foreeach loop with last item

我看过其他“PHP 变量被覆盖”的答案,但仍然无法弄明白。

我正在使用这个 PHP 在单个产品页面上获取所有产品类别标签:

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
if(is_array($terms)){
foreach ($terms as $term) {
    $product_cat_slug = $term->slug;
    $product_cat_slugs = ' product_cat-' . $product_cat_slug;
    echo $product_cat_slugs;
}
}

echo $product_cat_slugs; 输出 product_cat-category1 product_cat-category2.

问题是,当我从上面的函数中删除 echo $product_cat_slugs; 并在页面的其他地方使用 <?php echo $product_cat_slugs; ?> 时,我得到的输出只是最后一个类别 slug product_cat-category2,而不是两个类别 product_cat-category1 product_cat-category2.

怎么了? $product_cat_slugs 似乎在 foreach 之外被覆盖;我该如何预防?

如何在循环外输出 product_cat-category1 product_cat-category2

我建议添加字符串,例如

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );

if( is_array( $terms ) ) {
    $product_cat_slugs = ''; //Define the variable outside of the loop
    foreach ( $terms as $term ) {
        $product_cat_slugs .= ' product_cat-' . $term->slug; //Append the slug onto the string that already exists
    }
    echo $product_cat_slugs; //Echo the string outside of the loop so it only occurs once.
}