【问题标题】:How to convert an array to comma-separated string with placeholders for each array item?如何将数组转换为逗号分隔的字符串,每个数组项都有占位符?
【发布时间】:2015-10-09 06:36:44
【问题描述】:

我有一个变量$input,其中包含一个包含可变数量项目的数组。

如何创建一个逗号分隔的字符串,如下例所示,为每个值显示一个问号并在每个问号周围加上引号?

我尝试使用以下内容,但这会将所有问号括在一个引号中,而不是在每个问号周围加上引号:

我的尝试:

$output = implode(",", array_fill(0, count($input), "?"));

示例数组:

array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
  [4]=>
  string(1) "5"
}

预期输出:

$output = "?", "?", "?", "?", "?"

当前输出:

$output = "?, ?, ?, ?, ?"

【问题讨论】:

  • $output = implode(",", array_fill(0, count($input), "?")); 不会将任何内容用引号括起来......您代码中的其他内容必须将引号放在 $output; 周围。但如果您需要引号,请使用 $output = implode('", "', array_fill(0, count($input), "?"));
  • @MarkBaker:谢谢。这只是为了显示当前输出和预期输出之间的差异,抱歉。我的意思是我需要在每个问号周围加上引号。
  • @MarkBaker:我尝试了你的方法,这与我需要的很接近,但这里的输出缺少第一个问号的左引号和最后一个问号的右引号。
  • 好吧,我想你可以自己想出一个简单的字符串连接。完整答案:$output = '"' . implode('", "', array_fill(0, count($input), "?")) .'"';

标签: php arrays string replace


【解决方案1】:

试试这个:

$output = implode( ", ", array_fill(0, count($input), "\"?\"" ));

【讨论】:

  • 非常感谢 - 这很好用。我会尽快接受。 :)
【解决方案2】:

你可以这样做。

https://eval.in/401410

代码

<?php 
$K= array("1","2","3","4","5");
$P=preg_filter('/^(.*)/', '"?"', $K);
echo implode(",",$P);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2020-05-21
    • 2011-06-18
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多