IM使用下面的代碼輸出數組如何把一個變量在引號
$values = array();
foreach ($album as $a){
$values[] = $a['value'];
}
$string = implode(' or ', $values);
}
返回
1 or 2 or 3
現在我怎樣才能把「」 arouns每個值,所以看起來像
"1" or "2" or "3"
感謝所有幫助
IM使用下面的代碼輸出數組如何把一個變量在引號
$values = array();
foreach ($album as $a){
$values[] = $a['value'];
}
$string = implode(' or ', $values);
}
返回
1 or 2 or 3
現在我怎樣才能把「」 arouns每個值,所以看起來像
"1" or "2" or "3"
感謝所有幫助
if (!empty($values)) {
$string = '"' . implode('" or "', $values) . '"';
} else {
$string = 'What do you think you\'re doing!?';
}
這隻會引用整個事情,而不是不同的陣列部分。 –
@Alex,OP想要的字符串輸出,而不是數組。 – 65Fbef05
不是我的意思,但我只是注意到「或」的引號,所以我錯了,這將起作用。 –
這在我看來是比較容易:
$values = array();
foreach ($album as $a){
$values[] = '"'.$a['value'].'"'; //concat quotes on each side of the value
}
$string = implode(' or ', $values);
}
這裏有一個乾淨的解決方案,將與空數組正常工作:
$string = implode(' or ', array_map(function($value) {
return '"' . $value . '"';
}, $values));
演示(從php -a
外殼複製):
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 >
可能是最簡潔的解決方案,但也是最難讀的。 –
那麼,這個例子很難閱讀。代碼本身非常易讀 – ThiefMaster
你嘗試了什麼?它有用嗎?如果不是,爲什麼不呢?我不會downvote(主要是由於-3已經),但只是做它;-) – 2012-06-26 20:32:40