PHP使用AND添加逗号到项目

Sam*_*ida 9 php csv loops

我想在除最后一项之外的每个项目中添加逗号.最后一个必须有"和".

第1项,第2项和第3项

但物品可以从1 +

所以如果1项:

第1项

如果2项:

第1项和第2项

如果3项:

第1项,第2项和第3项

如果4项:

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

等等

Ry-*_*Ry- 10

这是一个功能; 只是传递数组.

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);
}
Run Code Online (Sandbox Code Playgroud)

演示