我有以下代码可以使用:
$apple_color = "red";
$pear_color = "green";
$banana_color = "yellow";
$grape_color = "purple";
foreach(array("apple","pear","banana","grape") as $idx=>$fname) {
$var = "${fname}_color";
echo "$var = ${$var}<br>".PHP_EOL;
}
但是,我无法弄清楚如何通过消除$ var变量来缩短代码:
foreach(array("apple","pear","banana","grape") as $idx=>$fname) {
echo "${fname}_color = ${${fname}_color}<br>".PHP_EOL;
}
&#34; $ {$ {fname} _color&#34;返回一个PHP错误,指出&#34;语法错误,意外&#39; _color&#39; (T_STRING)&#34;
答案 0 :(得分:1)
这个怎么样?使用${'string'}
构建
foreach(["apple","pear","banana","grape"] as $fname) {
echo "{$fname}_color = ".${$fname.'_color'}."<br>".PHP_EOL;
}
答案 1 :(得分:1)
不是为每种颜色设置单独的变量,而是将颜色存储在由水果名称索引的数组中。这样就可以避免使用变量变量。
$colors = [
'apple' => 'red',
'pear' => 'green',
'banana' => 'yellow',
'grape' => 'purple'
];
foreach (["apple","pear","banana","grape"] as $fname) {
echo "{$fname}_color = $colors[$fname]<br>".PHP_EOL;
}
答案 2 :(得分:0)
使用字符串格式来简化您的生活:
echo sprintf('$%s_color = %s<br>' . PHP_EOL, $fname, ${$fname . '_color'});