将文本与变量中的变量连接起来?

我正在尝试使用循环创建一小段 HTML 代码。在循环中,我想获取$start_intro_headline_X下面简化代码中的每个文本值。我该如何解决这个问题?


$start_intro_headline_0 = "This is the first headline";

$start_intro_headline_1 = "This is the second headline";


$intro_sections ="";


for ($x = 0; $x <= 4; $x++) {

$intro_sections .= "<h2>{$start_intro_headline_{$x}}</h2>"; <-- THIS LINE IS THE PROBLEM!


$pageContent = <<<EOD

$intro_sections

EOD;


翻翻过去那场雪
浏览 181回答 2
2回答

幕布斯6054654

您需要将变量的名称作为字符串分配给另一个变量,然后将其用作变量变量。我知道这听起来令人困惑,所以只需查看代码:) 以下是代码解释:$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++) {&nbsp; $var = 'start_intro_headline_'.$x;&nbsp; $intro_sections .= "<h2>{$$var}</h2>"; // Note that it's $$var, not $var}&nbsp;echo $intro_sections;该echo会产生<h2>This is the first headline</h2><h2>This is the second headline</h2>

肥皂起泡泡

虽然我认为另一个答案有效,但避免动态变量会更安全。使用数组来保存您的值:$start_intro_headline = [&nbsp; "This is the first headline",&nbsp; "This is the second headline"];$intro_sections ="";$total = count($start_intro_headline);for ($x = 0; $x < $total; $x++) {&nbsp; $intro_sections .= "<h2>{$start_intro_headline[$x]}</h2>";}&nbsp;echo $intro_sections;这样您以后就不必创建新变量,只需向数组添加新值即可。下面是使用动态变量可能会出错的示例。
打开App,查看更多内容
随时随地看视频慕课网APP