【问题标题】:How to remove the last comma of a Wordpress php foreach output?如何删除 Wordpress php foreach 输出的最后一个逗号?
【发布时间】:2022-01-23 20:14:28
【问题描述】:

我已经尝试了一些修剪等等,但没有任何效果。

也许我犯了一个错误,你能帮助我吗?代码目前看起来像这样:

$post = get_post();
$terms = wp_get_post_terms($post->ID, 'genre');
if ($terms)
{
    $output = '';
    foreach ($terms as $term) {
      $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a>, ';
    }
};
echo $output;

【问题讨论】:

    标签: php wordpress foreach


    【解决方案1】:

    尝试输入substr_replace($term-&gt;name,"",-1),查看documentation 了解更多信息,这应该会从最后一个字符串中删除逗号。

    【讨论】:

    • 不,总是删除所有输出的最后一个字符,但不删除逗号。可能是因为我在 "," 之后设置了逗号?
    【解决方案2】:

    只需添加一个计数器来检查数组的最后一项

    $post = get_post();
    $terms = wp_get_post_terms($post->ID, 'genre');
    if ($terms)
    {
        $output = '';
        $i = 0;
        foreach ($terms as $term) {
          $output .= '<a href="' . get_term_link($term->slug, 'genre') . '">' . $term->name . '</a> ';
    
          $output .= ($i == count($terms) - 1) ? '' : ',';
          $i++;
        }
    };
    echo $output;
    

    【讨论】:

    • 什么作用?和:做,你能告诉我吗,我到处都在寻找它,但似乎找不到正确的解释
    • 如果条件为真,添加?之后的部分,否则添加:之后的部分
    • 谢谢@YazanFouadAldbaisy,但这无济于事。现在看起来像“Animation ,Familie ,Fantasy ,Musical ”(见“Musical”后面的最后一个逗号)
    • 代码工作正常,检查你的条款,也许音乐后面有一个没有名字的。
    • 我查过了——没有别的名字:/逗号后面有空格是正常的吗?就像您在输出上方看到的那样,首先放置名称,然后是空格,然后是逗号。它应该是“动画……”而不是“动画……”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2012-09-23
    • 2016-07-25
    • 2020-01-24
    • 2013-11-24
    相关资源
    最近更新 更多