为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
翻翻过去那场雪 2021-07-01 13:12:14
我正在尝试使用循环创建一小段 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_sectionsEOD;
查看完整描述

2 回答

?
幕布斯6054654

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>


查看完整回答
反对 回复 2021-07-09
?
肥皂起泡泡

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;

这样您以后就不必创建新变量,只需向数组添加新值即可。下面是使用动态变量可能会出错的示例。


查看完整回答
反对 回复 2021-07-09
  • 2 回答
  • 0 关注
  • 180 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信