如何将数组中的元素转换为格式化的csv格式?PHP


How to convert elements in an array to a formatted csv form? PHP

我有一个数组,如下所示;

$carsarray = array("audi","toyota","ford");

我想生成一个字符串像;

'audi','toyota','ford'

使用内爆函数类似;

$cars = implode(",",$carsarray);

我得到像一样的输出

audi,toyota,ford

为了获得我想要的输出,我使用;

$cars = "";
foreach($carsarray as $car){
    $cars .= "'".$car."',";
}
$cars = rtrim($cars,","); // this gives me 'audi','toyota','ford'

但是,除了使用这些foreachwhile或其他一些循环之外,还有其他更好/有效的方法吗?我的意思是,类似内爆函数的东西?

Try-

$cars = "'" . implode("','", $carsarray) . "'";

您可以使用此

$cars = "'".implode("','",$carsarray)."'";

尝试使用这个:

$carsarray = array("audi","toyota","ford");
$your_result = "'";
$your_result .= implode("','",$carsarray);
$your_result .= "'";