PHP中数组的串行逗号

bay*_*uah 2 php native function

我试图从数组中创建字符串序列逗号.这是我使用的代码:

<?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{
        // If >=2 then regular merger 
        $rturn=implode($konj,$ari); 
    }; 
    // Return 
    return $rturn; 
 }; 
?>
Run Code Online (Sandbox Code Playgroud)

从而:

<?php
    $eat = array_to_serial_comma(array('satay','orange','rambutan'));
    echo "I eat $eat";
?>
Run Code Online (Sandbox Code Playgroud)

结果:

I eat satay, orange, and rambutan
Run Code Online (Sandbox Code Playgroud)

是否有更有效的方法,使用本机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; 
 }; 
?>
Run Code Online (Sandbox Code Playgroud)

Mas*_*ash 8

这是一个更清洁的方式:

<?php
    $array = array('satay','orange','rambutan');
    $last = array_pop($array);
    echo "I eat " . implode(', ', $array) . ", and " . $last;
?>
Run Code Online (Sandbox Code Playgroud)

array_pop() 将最后一个元素从数组中取出并分配给它 $last

  • 此外,使用一个空数组,它将显示"我吃和"...并且只有一个元素的数组,il将产生"我吃和沙爹" (2认同)