我正在尝试从数组中创建字符串serial comma。这是我使用的代码:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
但我得到的结果是:
I eat satay, orange, rambutan
不能:
I eat satay, orange, and rambutan
然而!
所以,我创造了自己的功能:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
// Reverse array
$ariBlk=array_reverse($ari,false);
foreach($ariBlk as $no=>$c){
if($no>=(count($ariBlk)-1)){
$rturn[]=$c.$delimiter;
}else{
$rturn[]=($no==0)?
$konj.$c
: $space.$c.$delimiter;
};
};
// Reverse array
// to original
$rturn=array_reverse($rturn,false);
$rturn=implode($rturn);
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
因此:
<?php
$eat = array_to_serial_comma(array('satay','orange','rambutan'));
echo "I eat $eat";
?>
结果:
I eat satay, orange, and rambutan
是否有更有效的方法,可能使用本机PHP函数?
修改
基于@Mash的代码,我修改了可能有用的代码:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
$akr = array_pop($ari);
$rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr;
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
答案 0 :(得分:8)
这是一个更清洁的方式:
<?php
$array = array('satay','orange','rambutan');
$last = array_pop($array);
echo "I eat " . implode(', ', $array) . ", and " . $last;
?>
array_pop()
从数组中取出最后一个元素并将其分配给$last
答案 1 :(得分:1)
<?php
$arr = array('satay','orange','rambutan');
print("I eat ".implode(", ", array_slice($arr, 0, count($arr)-1))." and ".$arr[count($arr)-1]);
?>
答案 2 :(得分:1)
试试这样:
$array = array('satay','orange','rambutan');
echo "I eat ".join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1))));
重复问题:Implode array with ", " and add "and " before last item
答案 3 :(得分:0)
<?php
$arr = array('satay','orange','rambutan');
$lastElement = array_pop($arr);
echo "I eat " . implode(', ',$arr)." and ".$lastElement;
?>
这将导致相同的结果: 我吃沙爹,橘子和红毛丹
答案 4 :(得分:0)
这个怎么样?
function render_array_as_serial_comma($items) {
$items = $variables['items'];
if (count($items) > 1) {
$last = array_pop($items);
return implode(', ', $items) . ' and ' . $last;
}
return array_pop($items);
}
这应该做到以下几点:
echo render_array_as_serial_comma(array('a'));
echo render_array_as_serial_comma(array('a', 'b'));
echo render_array_as_serial_comma(array('a', 'b', 'c'));
a
a and b
a, b and c