我有一些数据库字段叫做
picture1_en
picture2_en
...
picture1_de
picture2_de
...
picture1_it
picture2_it
是的,它可以用另一种方式实现,但我不能改变实现方式。
假设我有一个名为 $lang 的变量,其中包含“de”或“en”或“it”
现在,如果我想打印这个值,我可以使用这个:
for($i=1; $i<=10; ++$i)
echo $r["picture$i_$lang"];
问题是 PHP 将下划线解释为变量名的一部分(例如,它将其解释为“$i_”)。我尝试了很多疯狂的方法来转义下划线,但都没有用。
当然可以
echo $r["picture".$i."_".$lang];
但我想知道是否有办法强制 PHP 将“_”解释为字符串文字,而不是变量名的一部分。
最佳答案
您可以使用花括号分隔字符串中的变量名边界(仅限双引号)
$r["picture{$i}_{$lang}"];
或
$r["picture${i}_${lang}"];
http://php.net/manual/en/language.types.string.php
复杂( curl )语法
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:
关于php - 在PHP中,如何在两个变量名之间添加下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805883/