爆与",&QUOT阵列;并添加"和"最后一个项目之前, [英] Implode array with ", " and add "and " before last item

查看:115
本文介绍了爆与",&QUOT阵列;并添加"和"最后一个项目之前,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个数组包含的项目列表,我希望把它变成一个字符串,但我不知道如何让最后一个项目有一个&安培; /之前它,而不是昏迷

This array holds a list of items, 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 coma.

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

或者,如果你的真正的preFER的冗长:

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.

这篇关于爆与",&QUOT阵列;并添加"和"最后一个项目之前,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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