When I implode my array I get a list that looks like this:
当我内爆我的数组时,我得到一个如下所示的列表:
qwerty, QTPQ, FRQO
I need to add single quotes so it looks like:
我需要添加单引号,所以它看起来像:
'qwerty', 'QTPQ', 'FRQO'
Can this be done using PHP?
可以使用PHP完成吗?
4 个解决方案
#1
18
Use '
before and after implode()
使用'内爆前后()
$temp = array("abc","xyz");
$result = "'" . implode ( "', '", $temp ) . "'";
echo $result; // 'abc', 'xyz'
#2
0
You can set the glue to ', '
and then wrap the result in '
您可以将胶水设置为','然后将结果包装在'
$res = "'" . implode ( "', '", $array ) . "'";
#3
0
Similar to what Rizier123 said, PHP's implode method takes two arguments; the "glue" string and the "pieces" array.
与Rizier123所说的类似,PHP的implode方法有两个参数; “胶水”字符串和“件”数组。
so,
$str = implode(", ", $arr);
gives you the elements separated by a comma and a space, so
为您提供以逗号和空格分隔的元素
$str = implode("', '", $arr);
gives you the elements separated by ', '
.
为您提供以','分隔的元素。
From there all you need to do is concatenate your list with single quotes on either end.
从那里你需要做的就是在两端用单引号连接你的列表。
#4
0
Here is another way:
这是另一种方式:
$arr = ['qwerty', 'QTPQ', 'FRQO'];
$str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));
echo $str; //'qwerty', 'QTPQ', 'FRQO'
sprintf() is a clean way of wrapping the single quotes around each item in the array
sprintf()是一种在数组中的每个项目周围包装单引号的简洁方法
array_map() executes this for each array item and returns the updated array
array_map()为每个数组项执行此操作并返回更新的数组
implode() then turns the updated array with into a string using a comma as glue
implode()然后使用逗号作为粘合将更新的数组转换为字符串
#1
18
Use '
before and after implode()
使用'内爆前后()
$temp = array("abc","xyz");
$result = "'" . implode ( "', '", $temp ) . "'";
echo $result; // 'abc', 'xyz'
#2
0
You can set the glue to ', '
and then wrap the result in '
您可以将胶水设置为','然后将结果包装在'
$res = "'" . implode ( "', '", $array ) . "'";
#3
0
Similar to what Rizier123 said, PHP's implode method takes two arguments; the "glue" string and the "pieces" array.
与Rizier123所说的类似,PHP的implode方法有两个参数; “胶水”字符串和“件”数组。
so,
$str = implode(", ", $arr);
gives you the elements separated by a comma and a space, so
为您提供以逗号和空格分隔的元素
$str = implode("', '", $arr);
gives you the elements separated by ', '
.
为您提供以','分隔的元素。
From there all you need to do is concatenate your list with single quotes on either end.
从那里你需要做的就是在两端用单引号连接你的列表。
#4
0
Here is another way:
这是另一种方式:
$arr = ['qwerty', 'QTPQ', 'FRQO'];
$str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));
echo $str; //'qwerty', 'QTPQ', 'FRQO'
sprintf() is a clean way of wrapping the single quotes around each item in the array
sprintf()是一种在数组中的每个项目周围包装单引号的简洁方法
array_map() executes this for each array item and returns the updated array
array_map()为每个数组项执行此操作并返回更新的数组
implode() then turns the updated array with into a string using a comma as glue
implode()然后使用逗号作为粘合将更新的数组转换为字符串