我建议您将您的问题视为一个可以进行单元测试的函数,以便更容易构建并且您可以灵活地解决您的解决方案。
- 使用计数器跟踪您的数组:总计、第一个块、尾部
- 考虑任何特殊情况,例如 2 个元素、3 个元素等。
- 使用
array_pop 获取最后一项
- 使用
array_slice 从“take N”参数中获取第一个块。
- 根据需要进行内爆和连接以获得所需的结果
这是一个例子。
<?php
function niceAuthorsPrint(array $authors, $takeCount){
$totalAuthors = count( $authors );
$tailCount = $totalAuthors - $takeCount;
$first = array_slice($authors, 0, $takeCount);
$othersLabel = $tailCount == 1 ? 'other' : 'others';
$string = implode( ", ", $first );
if($tailCount > 0){
$string .= " and " . $tailCount . ' ' . $othersLabel;
}
return $string;
}
// take 3
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 3) ."\n";
// take 4
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 4) ."\n";
// take 5
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";
?>
将输出:
user1, user2, user3 and 2 others
user1, user2, user3, user4 and 1 other
user1, user2, user3, user4, user5
Working example here
另类
处理特殊情况和打印最后一项值的替代方法。
<?php
// array of authors, number of authors to take first
function niceAuthorsPrint(array $authors, $takeCount){
$totalAuthors = count( $authors );
if($totalAuthors >= 3 && $takeCount >= $totalAuthors)
{
$takeCount = 2;
}
if($totalAuthors == 2 && $takeCount >= $totalAuthors)
{
$takeCount = 1;
}
$last = array_pop($authors);
$tailCount = $totalAuthors - $takeCount;
$first = array_slice($authors, 0, $takeCount);
$othersLabel = $tailCount == 1 ? $last : $tailCount . ' others';
$string = implode( ", ", $first );
if($tailCount > 0){
$string .= " and " . $othersLabel;
}
return $string;
}
// take 3
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 3) ."\n";
// take 4
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 4) ."\n";
// take 5
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";
// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3', 'user4', 'user5' ), 5) ."\n";
// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2', 'user3'), 3) ."\n";
// take original count, take first three as default
echo niceAuthorsPrint(array( 'user1', 'user2'), 2) ."\n";
将打印:
user1, user2, user3 and 2 others
user1, user2, user3, user4 and user5
user1, user2 and 3 others
user1, user2 and 3 others
user1, user2 and user3
user1 and user2
根据您的需要随意调整。
Working code example