在PHP中为项目添加逗号,并在末尾附近使用“和”。

11

我想在每个项目后面都加上逗号,除了最后一个,最后一个必须是 “和”。

项目1,项目2和项目3

但是项目数量可以是 1 +

所以如果只有一个项目:

项目1

如果有两个项目:

项目1和项目2

如果有三个项目:

项目1,项目2和项目3

如果有四个项目:

项目1,项目2,项目3和项目4

等等等等。


6
或者,你可以使用牛津逗号(Oxford comma),这同样是正确的(对于“正确”的略微不同的价值观)。 :-) - ghoti
1
格式有多可预测?显然不能只在每个空格字符处拆分项。它们都叫做/ [Ii] tem [0-9]+ /吗?您不希望出现“Item,1,Item,2,Item和3”。那么...我们的输入是字符串还是数组? - Graham
7个回答

10

这里有一个函数可以做到这一点,只需传递数组即可。

function make_list($items) {
    $count = count($items);

    if ($count === 0) {
        return '';
    }

    if ($count === 1) {
        return $items[0];
    }

    return <a rel="nofollow" href="https://php.net/implode">implode</a>(', ', <a rel="nofollow" href="https://php.net/array_slice">array_slice</a>($items, 0, -1)) . ' and ' . <a rel="nofollow" href="https://php.net/end">end</a>($items);
}

演示


3

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"

没有别的意思,只是想提出这一点。


1
这是一种变体,它具有支持有争议的牛津逗号的选项,并采用连词(和/或)的参数。请注意,还需要检查两个项目;即使是牛津逗号的支持者在这种情况下也不使用逗号。
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);
}

0
你可以这样做:
$items = array("Item 1", "Item 2", "Item 3", "Item 4");

$item = glueItems($items);

function glueItems($items) {
    if (count($items) == 1) {
        $item = implode(", ", $items);
    } elseif (count($items) > 1)  {
        $last_item = array_pop($items);
        $item = implode(", ", $items) . ' and ' . $last_item;
    } else {
        $item = '';
    }
    return $item;
}
echo $item;

如果只有一个项目,为什么需要使用implode呢? - rgbflawed

0

我的函数基于其他人的代码,但我觉得更加简洁。此外,它总是添加牛津逗号,因为实际上并没有关于是否使用它正确的“争议”或辩论。

//feed in an array of words to turn it into a written list.
//['bacon'] turn into just 'bacon'
//['bacon','eggs'] turns into 'bacon and eggs'
//['bacon','eggs','ham'] turns into 'bacon, eggs, and ham'
function writtenList($items) {

    //nothing, or not an array? be done with this
    if (!$items || !is_array($items)) return '';

    //list only one or two items long, this implosion should work fine
    if (count($items)<=2) {
        return implode(' and ',$items);
    //else take off the last item, implode the rest with just a comma and the remaining item
    } else {
        $last_item = array_pop($items);
        return implode(", ",$items).', and '.$last_item;
    }
}

0

您可以使用逗号将前X-1个项目合并,然后使用“和”添加最后一个项目。


为了通用性,如果列表中只有一个项目怎么办? - Peter Mortensen

-1

如果它是一个数组,只需使用implode(...)

例如:

$items = array("Item 1", "Item 2", "Item 3", "Item 4");
$items[count($items) - 1] = "and " . $items[count($items) - 1];
$items_string = implode(", ", $items);

echo $items_string;

演示:http://codepad.viper-7.com/k7xISG

错误的连接运算符。 - Ry-
3
这仍然会在最后一项前面添加一个不必要的逗号。OP示例中使用的是“and”,而非逗号。 - SimonMayer
1
@SimonMayer 在正式的英文中,在"AND"之前应该加上逗号。 - Naftali
1
@Neal:我认为现在省略逗号是可以接受的,而且这也是用户想要的。 (是的,我在“和”之前也使用逗号。) - Ry-
2
牛津逗号但打印错误并且 $items[0] 用于只包含一个元素的数组。 - Josh J
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接