【问题标题】:Adding a character before last word in PHP array [duplicate]在PHP数组中的最后一个单词之前添加一个字符[重复]
【发布时间】:2012-09-21 13:14:25
【问题描述】:

可能重复:
Implode array with “, ” and add “and ” before last item

在 Wordpress 中,我使用 PHP implode 用逗号分隔一系列字符串,这些字符串存储在一个数组中,如下所示:

Wordpress 循环遍历这个:

<?php unset($credits); ?>
<?php if(get_field('song_credits')):
    while(has_sub_field('song_credits')): 
       $credits[] = get_sub_field('artist_name');
    endwhile; ?>
    <p><?php echo implode(', ', $credits); ?>.</p>
<?php endif; ?>

基本上,一系列字符串存储到 $credits 数组中,然后我使用 implode 将每个字符串用逗号分隔。

我需要在最后一个单词之前添加一个 & 符号而不是逗号。这里可以吗?

【问题讨论】:

    标签: php arrays implode


    【解决方案1】:

    implode 不能直接做到这一点,但并不难:

    switch (count($credits)) {
        case 0:
            $result = '';
            break;
        case 1:
            $result = reset($credits);
            break;
        default:
            $last = array_pop($credits); // warning: this modifies the array!
            $result = implode(', ', $credits).' & '.$last;
            break;
    }
    

    【讨论】:

    • 这对我不起作用,但以下是:

    • @JCHASE11:如果你愿意测试它,它会是worked for you
    • 我在写回复之前确实做过测试。但是因为它确实有效,所以我会给你正确的答案……不必暴躁……谢谢。
    • 顺便说一句,以上是双关语,不是批评!
    【解决方案2】:

    取自:Implode array with ", " and add "and " before last item

    &lt;p&gt;&lt;?php echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($credits, 0, -1))), array_slice($credits, -1)))); ?&gt;&lt;/p&gt;

    这很好用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-06-13
      • 2013-07-05
      相关资源
      最近更新 更多