这个数组包含一个项目列表,我想把它变成一个字符串,但我不知道如何让最后一个项目有一个&/和它之前而不是昏迷.
1 => coke 2=> sprite 3=> fanta
Run Code Online (Sandbox Code Playgroud)
应该成为
coke, sprite and fanta
Run Code Online (Sandbox Code Playgroud)
这是常规的内爆功能:
$listString = implode(', ', $listArrau);
Run Code Online (Sandbox Code Playgroud)
什么是简单的方法呢?
dec*_*eze 103
适用于任意数量物品的长衬里:
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
Run Code Online (Sandbox Code Playgroud)
或者,如果你真的更喜欢冗长:
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
echo join(' and ', $both);
Run Code Online (Sandbox Code Playgroud)
关键是这个切片,合并,过滤和连接处理所有情况,包括0,1和2项,没有额外的if..else语句.它恰好可以折叠成一个单行.
Ang*_*Dan 72
我不确定单个班轮是解决这个问题最优雅的方法.
我刚刚写了这篇文章并根据需要删除它:
/**
* Join a string with a natural language conjunction at the end.
* https://gist.github.com/angry-dan/e01b8712d6538510dd9c
*/
function natural_language_join(array $list, $conjunction = 'and') {
$last = array_pop($list);
if ($list) {
return implode(', ', $list) . ' ' . $conjunction . ' ' . $last;
}
return $last;
}
Run Code Online (Sandbox Code Playgroud)
您不必使用"和"作为您的连接字符串,它非常有效,可以处理从0到无限数量项目的任何内容:
// null
var_dump(natural_language_join(array()));
// string 'one'
var_dump(natural_language_join(array('one')));
// string 'one and two'
var_dump(natural_language_join(array('one', 'two')));
// string 'one, two and three'
var_dump(natural_language_join(array('one', 'two', 'three')));
// string 'one, two, three or four'
var_dump(natural_language_join(array('one', 'two', 'three', 'four'), 'or'));
Run Code Online (Sandbox Code Playgroud)
Jer*_*cSi 25
您可以弹出最后一项,然后将其与文本一起加入:
$yourArray = ('a', 'b', 'c');
$lastItem = array_pop($yourArray); // c
$text = implode(', ', $yourArray); // a, b
$text .= ' and '.$lastItem; // a, b and c
Run Code Online (Sandbox Code Playgroud)
Enr*_*que 15
试试这个:
$str = array_pop($array);
if ($array)
$str = implode(', ', $array)." and ".$str;
Run Code Online (Sandbox Code Playgroud)