-1

可能重复:
使用“,”内爆数组并在最后一项之前添加“和”

在 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 将每个字符串用逗号分隔。

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

4

2 回答 2

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;
}
于 2012-09-21T13:19:20.683 回答
0

取自:带有“,”的内爆数组,并在最后一项之前添加“和”

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

这很好用

于 2012-09-21T13:23:48.790 回答