我想给除最后一项之外的每一项都加一个逗号。最后一个必须有"and“。
项目1、项目2和项目3
但项目可以来自1+
因此,如果有一项:
项目1
如果有两项:
项目1和项目2
如果有三项:
项目1、项目2和项目3
如果有四个项目:
项目1、项目2、项目3和项目4
等等。
发布于 2012-01-30 23:08:31
下面是一个函数;只需传递数组即可。
function make_list($items) {
$count = count($items);
if ($count === 0) {
return '';
}
if ($count === 1) {
return $items[0];
}
return implode(', ', array_slice($items, 0, -1)) . ' and ' . end($items);
}
发布于 2012-01-31 13:02:39
minitech在一开始的解决方案是优雅的,除了一个小问题,他的输出将导致:
var_dump(makeList(array('a', 'b', 'c'))); //Outputs a, b and c
但是这个列表(有待讨论)的正确格式应该是: a、b和c。在他的实现中,倒数第二个属性永远不会有',‘附加到它后面,因为数组切片在将它传递给implode()
时将其视为数组的最后一个元素。
这是我的一个实现,并且正确地(再次讨论)格式化了这个列表:
class Array_Package
{
public static function toList(array $array, $conjunction = null)
{
if (is_null($conjunction)) {
return implode(', ', $array);
}
$arrayCount = count($array);
switch ($arrayCount) {
case 1:
return $array[0];
break;
case 2:
return $array[0] . ' ' . $conjunction . ' ' . $array[1];
}
// 0-index array, so minus one from count to access the
// last element of the array directly, and prepend with
// conjunction
$array[($arrayCount - 1)] = $conjunction . ' ' . end($array);
// Now we can let implode naturally wrap elements with ','
// Space is important after the comma, so the list isn't scrunched up
return implode(', ', $array);
}
}
// You can make the following calls
// Minitech's function
var_dump(makeList(array('a', 'b', 'c')));
// string(10) "a, b and c"
var_dump(Array_Package::toList(array('a', 'b', 'c')));
// string(7) "a, b, c"
var_dump(Array_Package::toList(array('a', 'b', 'c'), 'and'));
string(11) "a, b, and c"
var_dump(Array_Package::toList(array('a', 'b', 'c'), 'or'));
string(10) "a, b, or c"
并不反对另一种解决方案,只是想提出这一点。
发布于 2019-03-05 03:21:23
下面是一个变种,它可以选择支持有争议的Oxford Comma,并接受合取(和/或)的参数。注意两个项目的额外检查;在这种情况下,即使是牛津的支持者也不使用逗号。
function conjoinList($items, $conjunction='and', $oxford=false) {
$count = count($items);
if ($count === 0){
return '';
} elseif ($count === 1){
return $items[0];
} elseif ($oxford && ($count === 2)){
$oxford = false;
}
return implode(', ', array_slice($items, 0, -1)) . ($oxford? ', ': ' ') . $conjunction . ' ' . end($items);
}
https://stackoverflow.com/questions/9065929
复制相似问题