<分区>
我想为除最后一项以外的所有项目添加一个逗号。最后一个必须有“和”。
项目 1、项目 2 和项目 3
但元素可以来自1+
所以如果一个项目:
Item 1
如果有两个项目:
Item 1 and Item 2
如果三个项目:
Item 1, Item 2 and Item 3
如果有四个项目:
Item 1, Item 2, Item 3 and Item 4
等等等等
<分区>
我想为除最后一项以外的所有项目添加一个逗号。最后一个必须有“和”。
项目 1、项目 2 和项目 3
但元素可以来自1+
所以如果一个项目:
Item 1
如果有两个项目:
Item 1 and Item 2
如果三个项目:
Item 1, Item 2 and Item 3
如果有四个项目:
Item 1, Item 2, Item 3 and Item 4
等等等等
最佳答案
这是一个函数;只需传递数组即可。
function make_list($items) {
$count = count($items);
if ($count === 0) {
return '';
}
if ($count === 1) {
return $items[0];
}
return <a href="https://php.net/implode" rel="noreferrer noopener nofollow">implode</a>(', ', <a href="https://php.net/array_slice" rel="noreferrer noopener nofollow">array_slice</a>($items, 0, -1)) . ' and ' . <a href="https://php.net/end" rel="noreferrer noopener nofollow">end</a>($items);
}
关于php - 在 PHP 中向项目添加逗号并在末尾添加 "and",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9065929/