PHP 在逗号分隔列表中添加单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34440610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP add single quotes to comma separated list
提问by Tom Canfarotta
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 完成吗?
回答by Ypages Onine
Use '
before and after implode()
'
在 implode() 之前和之后使用
$temp = array("abc","xyz");
$result = "'" . implode ( "', '", $temp ) . "'";
echo $result; // 'abc', 'xyz'
回答by Klompenrunner
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() 然后使用逗号作为胶水将更新后的数组 with 转换为字符串
回答by Ashish pathak
$ids = array();
foreach ($file as $newaarr) {
array_push($ids, $newaarr['Identifiant']);
}
$ids =array_unique($ids);
//$idAll=implode(',',$ids);
$idAll = "'" . implode ( "', '", $ids ) . "'";
回答by Musa
You can set the glue to ', '
and then wrap the result in '
您可以将胶水设置为', '
然后将结果包裹在'
$res = "'" . implode ( "', '", $array ) . "'";
回答by jc_programmer
Similar to what Rizier123 said, PHP's implodemethod takes two arguments; the "glue" string and the "pieces" array.
类似于 Rizier123 所说的,PHP 的implode方法需要两个参数;“glue”字符串和“pieces”数组。
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.
从那里您需要做的就是将您的列表与两端的单引号连接起来。