PHP将单引号添加到逗号分隔的列表中


PHP add single quotes to comma separated list

当我内爆数组时,我会得到一个列表,如下所示:

qwerty, QTPQ, FRQO

我需要添加单引号,这样看起来像:

'qwerty', 'QTPQ', 'FRQO'

这可以用PHP完成吗?

在内爆()前后使用'

$temp = array("abc","xyz");
$result = "'" . implode ( "', '", $temp ) . "'";
echo $result; // 'abc', 'xyz'

这里有另一种方法:

$arr = ['qwerty', 'QTPQ', 'FRQO'];
$str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));
echo $str; //'qwerty', 'QTPQ', 'FRQO'

sprintf()是一种将单引号括在数组中每个项目周围的干净方法

array_map()为每个数组项执行此操作,并返回更新后的数组

内爆()然后使用逗号作为粘合将更新后的数组转换为字符串

它也可以短如下:

sprintf("'%s'", implode("', '", $array))

您可以将胶水设置为', ',然后将结果包装在'

$res = "'" . implode ( "', '", $array ) . "'";

http://codepad.org/bkTHfkfx

与Rizier123所说的类似,PHP的内爆方法采用两个参数;"胶水"字符串和"碎片"数组。

所以,

$str = implode(", ", $arr);

提供了用逗号和空格分隔的元素,因此

$str = implode("', '", $arr);

提供了由', '分隔的元素。

从那里开始,你所需要做的就是将你的列表两端用单引号连接起来。

    $ids = array();
    foreach ($file as $newaarr) {
        array_push($ids, $newaarr['Identifiant']);
    }
   $ids =array_unique($ids);
    //$idAll=implode(',',$ids);
     $idAll = "'" . implode ( "', '", $ids ) . "'";

您可以在PHP中使用名为'implode'的方法。这将帮助您将所有数组值与给定的分隔符连接起来。

$arr = ['qwe', 'asd', 'zxc'];
echo implode(',', array_map(function($i){return "'".$i."'";}, $arr));

您的输出将如下所示:

'qwe','asd','zxc'
function implode_string($data, $str_starter = "'", $str_ender = "'", $str_seperator = ",") {
    if (isset($data) && $data) {
        if (is_array($data)) {
            foreach ($data as $value) {
                $str[] = $str_starter . addslashes($value) . $str_ender . $str_seperator;
            }
            return (isset($str) && $str) ? implode($str_seperator, $str) :  null;
        }
        return $str_starter . $data . $str_ender;
    }
}