【问题标题】:how to put a variable in quotes如何将变量放在引号中
【发布时间】:2012-06-28 05:57:40
【问题描述】:

我用下面的代码输出一个数组

$values = array();
foreach ($album as $a){
$values[] = $a['value'];
}

$string = implode(' or ', $values);

}

返回

 1 or 2 or 3

现在我怎样才能在每个值周围加上“”,所以它看起来像

 "1" or "2" or "3"

感谢您的帮助

【问题讨论】:

  • 你尝试了什么?它奏效了吗?如果不是,为什么不呢?我不会投反对票(主要是因为 -3 已经),但是就去做吧 ;-)

标签: php arrays variables quotes


【解决方案1】:
if (!empty($values)) {
    $string = '"' . implode('" or "', $values) . '"';
} else {
    $string = 'What do you think you\'re doing!?';
}

【讨论】:

  • 这只会引用整个内容,而不是不同的数组部分。
  • @Alex,OP 想要字符串输出,而不是数组。
  • 不是我的意思,但我只是注意到“或”上的引号所以我错了,这会起作用。
【解决方案2】:

我认为这更容易:

$values = array();
foreach ($album as $a){
$values[] = '"'.$a['value'].'"'; //concat quotes on each side of the value
}

$string = implode(' or ', $values);

}

【讨论】:

    【解决方案3】:

    这是一个干净的解决方案,可以在空数组中正常工作:

    $string = implode(' or ', array_map(function($value) {
        return '"' . $value . '"';
    }, $values));
    

    演示(复制自php -a shell):

    php > $values = array('foo', 'bar', 'moo');
    php >     $string = implode(' or ', array_map(function($value) {
    php (         return '"' . $value . '"';
    php (     }, $values));
    php > echo $string;
    "foo" or "bar" or "moo"
    php >
    

    【讨论】:

    • 可能是最简洁的解决方案,但也是最难阅读的。
    • 嗯,这个例子很难阅读。代码本身非常易读 imo
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2016-08-29
    • 1970-01-01
    相关资源
    最近更新 更多