用“and"从数组中分隔的列表在最后一个元素之前 [英] Comma separated list from array with "and" before last element

查看:25
本文介绍了用“and"从数组中分隔的列表在最后一个元素之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 ($number_list),它有一个动态生成的值列表.数组中至少有 1 个值,不超过 4 个.

I have an array ($number_list) that has a dynamically generated list of values. There will be at least 1 value in the array and no more than 4.

目前,我有一个很好的方法来使用逗号分隔的列表...

Currently, I have a nice way of having a comma separated list using this...

$comma_list = implode(', ', $number_list);

但是,我想保持英文惯例,并在最后一个元素之前加上and"这个词.所以,假设 $number_list 包含值 4, 5, 6, 7.我想回应这样的语句,列表是 4, 5, 6, and 7."

However, I'd like to keep with English convention and have the word "and" before the last element. So, let's say $number_list contains the values 4, 5, 6, 7. I would want to echo a statement like, "The list is 4, 5, 6, and 7."

任何想法如何将放在那里?

Any ideas how to get that and in there?

推荐答案

尝试 array_pop() 获取最后一个元素,然后 array_push 修改并将元素推回:

Try array_pop() to get the last element, then array_push to modify and push the element back:

http://php.net/manual/en/function.array-pop.php

类似的东西

$last_element = array_pop($number_list);
array_push($number_list, 'and '.$last_element);

然后你可以做你的内爆:

Then you can do your implode:

$comma_list = implode(', ', $number_list);

这篇关于用“and"从数组中分隔的列表在最后一个元素之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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