【问题标题】:PHP variable gets overwritten in foreeach loop with last itemPHP 变量在 foreach 循环中被最后一项覆盖
【发布时间】:2022-01-13 13:32:24
【问题描述】:

我查看了其他“覆盖 PHP 变量”的答案,但仍然无法弄清楚。

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

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

【问题讨论】:

  • 是的,您正在循环内覆盖它。你认为$product_cat_slugs = ' product_cat-' . $product_cat_slug; 还会做什么?决定如何保存所有结果,例如将它们全部放入数组或附加到现有字符串。
  • 我希望它们在循环外使用 echo $product_cat_slugs;product_cat-category1 product_cat-category2 一样输出。

标签: php wordpress woocommerce foreach


【解决方案1】:

我是否建议附加字符串,例如

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.
}

【讨论】:

  • 谢谢!这样可行。我看到 slug 是如何附加到字符串的。所有其他看似相似的答案都使用了不同的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 2015-07-04
  • 1970-01-01
相关资源
最近更新 更多