首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中,将逗号添加到项目和末尾附近的" and“

在PHP中,将逗号添加到项目和末尾附近的" and“
EN

Stack Overflow用户
提问于 2012-01-30 23:03:58
回答 7查看 2.1K关注 0票数 10

我想给除最后一项之外的每一项都加一个逗号。最后一个必须有"and“。

项目1、项目2和项目3

但项目可以来自1+

因此,如果有一项:

项目1

如果有两项:

项目1和项目2

如果有三项:

项目1、项目2和项目3

如果有四个项目:

项目1、项目2、项目3和项目4

等等。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2012-01-30 23:08:31

下面是一个函数;只需传递数组即可。

代码语言:javascript
复制
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);
}

Demo

票数 10
EN

Stack Overflow用户

发布于 2012-01-31 13:02:39

minitech在一开始的解决方案是优雅的,除了一个小问题,他的输出将导致:

代码语言:javascript
复制
var_dump(makeList(array('a', 'b', 'c'))); //Outputs a, b and c

但是这个列表(有待讨论)的正确格式应该是: a、b和c。在他的实现中,倒数第二个属性永远不会有',‘附加到它后面,因为数组切片在将它传递给implode()时将其视为数组的最后一个元素。

这是我的一个实现,并且正确地(再次讨论)格式化了这个列表:

代码语言:javascript
复制
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"

并不反对另一种解决方案,只是想提出这一点。

票数 2
EN

Stack Overflow用户

发布于 2019-03-05 03:21:23

下面是一个变种,它可以选择支持有争议的Oxford Comma,并接受合取(和/或)的参数。注意两个项目的额外检查;在这种情况下,即使是牛津的支持者也不使用逗号。

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9065929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档