在PHP中将数组转换为字符串

在PHP中将数组转换为字符串

问题描述:

我有一个类似PHP的数组:

i have an array like in PHP:

$a = array('110','111','121');

我想将其转换为:

$b = " '110' , '111' , '121' ";

PHP中有没有做过的功能?我知道这可以通过在数组上循环并在$ b中放入值来完成,但是我想要更少的代码解决方案.

is there any function in PHP that does it? i know it could be done with a loop on array and put value in $b, but i want a less more code solution.

谢谢.

您确实需要所有这些空格和引号吗?您仍然可以使用implode,尽管array_reduce可能更好

You do need all those spaces and quotes? You can still use implode, although array_reduce might be nicer

$a = array(1, 2, 3, 4);

$x = "'".implode("' , '", $a)."'";

array_reduce:

$x = array_reduce($a, function($b, $c){return ($b===null?'':$b.' , ')."'".$c."'";});

array_reduce的优点是,对于空数组(而不是''),您将获得NULL.请注意,您不能在5.3之前的php版本中使用此内联函数构造.您需要将回调函数设为单独的函数,并将其名称作为字符串传递给array_reduce.

Advantage of array_reduce, is that you will get NULL for an empty array, instead of ''. Note that you cannot use this inline function construct in php versions prior to 5.3. You'll need to make the callback a separate function and pass its name as a string to array_reduce.