2 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要將變量的名稱作為字符串分配給另一個(gè)變量,然后將其用作變量變量。我知道這聽起來令人困惑,所以只需查看代碼:) 以下是代碼解釋:
$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會(huì)產(chǎn)生<h2>This is the first headline</h2><h2>This is the second headline</h2>

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
雖然我認(rèn)為另一個(gè)答案有效,但避免動(dòng)態(tài)變量會(huì)更安全。使用數(shù)組來保存您的值:
$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;
這樣您以后就不必創(chuàng)建新變量,只需向數(shù)組添加新值即可。下面是使用動(dòng)態(tài)變量可能會(huì)出錯(cuò)的示例。
- 2 回答
- 0 關(guān)注
- 196 瀏覽
添加回答
舉報(bào)