PHP 形成字符串“A、B、C 和 D”从数组值
给定以下数组:
Array
(
[143] => Car #1
[144] => Car #2
[145] => Car #3
)
我目前正在使用它
implode(', ', array_values($car_names))
来生成类似的字符串
1 号车、2 号车、3 号车
我实际上想要得到类似的东西
1 号车、2 号车和 3 号车
这个想法是在数组的最后两个元素之间插入 " 和 "。
如果数组恰好包含两个键/值对(例如,用户有 2 辆车),则不会有逗号。
1 号车和 2 号车
如果数组包含一个键/值(例如,用户有 1 辆车)
1 号车
有什么建议如何完成这个任务吗?我尝试使用 array_splice ,但我不确定这是否可行(即向数组中插入新元素)。
感谢您的帮助!
Given the following array:
Array
(
[143] => Car #1
[144] => Car #2
[145] => Car #3
)
I am currently using this
implode(', ', array_values($car_names))
to generate a string like
Car #1, Car #2, Car #3
I would like to actually get something like
Car #1, Car #2 and Car #3
The idea would be to insert " and " between the two last elements of the array.
If the array happens to contain two key/value pairs (eg, user has 2 cars), there would be no commas.
Car #1 and Car #2
And if the array contains one key/value (eg, user has 1 car)
Car #1
Any suggestion how to get this done? I tried using array_splice
but I'm not sure that's the way to go (ie, inserting a new element into the array).
Thanks for helping!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我想你可能想要这样的东西,使用
array_pop
< /a> 获取数组末尾的最后一个元素。然后,您可以内爆数组的其余部分,并以自定义方式添加最后一个元素:编辑:添加条件以检查数组是否只有一个元素。
I think you probably want something like this, using
array_pop
to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:Edit: added conditional to check if the array had only one element.
preg_replace 可以查找最后一个命令,只需将其交换为
and
A preg_replace can look for the last command just just swap it to an
and
这个解决方案有点长,但经过了所有数组大小的测试,它是一个完整的解决方案。此外,它不会像上面的答案那样修改数组,而是被分成一个函数。
压缩版本具有丑陋的格式并忽略初始化变量等良好实践:
This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn't modify the array like the above answers and is separated into a function.
Compacted version with ugly formatting and ignoring good practices like initializing variables:
我不确定是否有内置函数,但类似的东西应该可以工作。
I'm not sure there's a built in function for this, but something like this should work.
这是我上面的评论中命名的函数的示例:
strrpos()
- 查找字符串中子字符串最后一次出现的位置substr()
- 返回字符串的一部分和代码:
That's an example with the functions named in my comment above:
strrpos()
- Find the position of the last occurrence of a substring in a stringsubstr()
- Return part of a stringand the code:
有多种方法可以做到这一点。这是另一个。
输出
There are a number of ways you could do this. Here's another.
Output