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"
没有反对其他解决方案,只是想提出这一点。