用“,"内爆一个数组并添加“和"在最后一项之前 [英] Implode an array with ", " and add "and " before the last item

查看:30
本文介绍了用“,"内爆一个数组并添加“和"在最后一项之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个数组保存了一个项目列表,我想把它变成一个字符串,但我不知道如何让最后一个项目有一个 &/and 而不是逗号.

This array holds a list of items, and I want to turn it into a string, but I don't know how to make the last item have a &/and before it instead of a comma.

1 => coke 2=> sprite 3=> fanta

应该变成

coke, sprite and fanta

这是常规的内爆函数:

$listString = implode(', ', $listArrau);

有什么简单的方法可以做到?

What's an easy way to do it?

推荐答案

适用于任意数量项目的长线:

A long-liner that works with any number of items:

echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));

或者,如果你真的更喜欢冗长:

Or, if you really prefer the verboseness:

$last  = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both  = array_filter(array_merge(array($first), $last), 'strlen');
echo join(' and ', $both);

关键是这种切片、合并、过滤和连接可以正确处理所有情况,包括 0、1 和 2 项,无需额外的 if..else 语句.而且它恰好可以折叠成单行.

The point is that this slicing, merging, filtering and joining handles all cases, including 0, 1 and 2 items, correctly without extra if..else statements. And it happens to be collapsible into a one-liner.

这篇关于用“,"内爆一个数组并添加“和"在最后一项之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆