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

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

问题描述

此数组包含一个项目列表,我想将其转换为字符串,但是我不知道如何使最后一个项目前带有&/而不是逗号.

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);

有什么简单的方法吗?

推荐答案

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

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天全站免登陆