2 回答
TA贡献1876条经验 获得超7个赞
您需要将变量的名称作为字符串分配给另一个变量,然后将其用作变量变量。我知道这听起来令人困惑,所以只需查看代码:) 以下是代码解释:
$start_intro_headline_0 = "This is the first headline";
$start_intro_headline_1 = "This is the second headline";
$intro_sections ="";
for ($x = 0; $x <= 1; $x++) {
$var = 'start_intro_headline_'.$x;
$intro_sections .= "<h2>{$$var}</h2>"; // Note that it's $$var, not $var
}
echo $intro_sections;
该echo会产生<h2>This is the first headline</h2><h2>This is the second headline</h2>
TA贡献1829条经验 获得超6个赞
虽然我认为另一个答案有效,但避免动态变量会更安全。使用数组来保存您的值:
$start_intro_headline = [
"This is the first headline",
"This is the second headline"
];
$intro_sections ="";
$total = count($start_intro_headline);
for ($x = 0; $x < $total; $x++) {
$intro_sections .= "<h2>{$start_intro_headline[$x]}</h2>";
}
echo $intro_sections;
这样您以后就不必创建新变量,只需向数组添加新值即可。下面是使用动态变量可能会出错的示例。
- 2 回答
- 0 关注
- 180 浏览
添加回答
举报