我试图从数组中创建字符串序列逗号.这是我使用的代码:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
Run Code Online (Sandbox Code Playgroud)
但结果我得到:
I eat satay, orange, rambutan
Run Code Online (Sandbox Code Playgroud)
不能:
I eat satay, orange, and rambutan
Run Code Online (Sandbox Code Playgroud)
然而!
所以,我做了自己的功能:
<?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{
// …Run Code Online (Sandbox Code Playgroud)