gpt4 book ai didi

php - PHP中数组的串行逗号

转载 作者:行者123 更新时间:2023-12-04 22:38:02 24 4
gpt4 key购买 nike

我正在尝试制作字符串 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

是否有更有效的方法,也许使用 native 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;
};
?>

最佳答案

这里有一个更简洁的方法:

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

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

关于php - PHP中数组的串行逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18209125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com