您的位置:首页 >PHP foreach 循环动态渲染标题与内容
发布于2026-04-16 阅读(0)
扫一扫,手机访问

本文讲解如何正确使用 PHP 的 foreach 循环遍历多维数组,将每个元素的 title、description 和 link 动态插入 HTML 模板中,避免重复输出静态字符串的问题。
在 PHP 中,若想从一个包含多个文章信息的数组(如 $articles)中逐个提取 title、description 和 link 并渲染到 HTML 结构中,不能预先拼接含固定变量的字符串再循环输出——否则所有项都会显示相同内容(如示例中 $str 始终使用初始 $title = 'Paragraph of text',导致三次输出完全一致)。
正确做法是:在循环体内动态获取当前元素的字段值,并实时嵌入 HTML 片段。以下是优化后的完整实现:
<?php
$articles = [
[
"title" => "Featured title 1",
"description" => "Paragraph of text beneath the heading to explain the heading. We'll add onto it with another sentence and probably just keep going until we run out of words.",
"link" => "page1.php",
],
[
"title" => "Featured title 2",
"description" => "Another compelling summary for the second feature.",
"link" => "page2.php",
],
[
"title" => "Featured title 3",
"description" => "A concise yet informative description for the third item.",
"link" => "page3.php",
],
];
// ✅ 正确:在 foreach 内部动态提取并插入数据
foreach ($articles as $article) {
echo '<div class="feature col">
<div class="feature-icon bg-primary bg-gradient">
<svg class="bi" width="1em" height="1em"><use xlink:href="#collection"></use></svg>
</div>
<h2>' . htmlspecialchars($article['title']) . '</h2>
<p>' . htmlspecialchars($article['description']) . '</p>
<a href="' . htmlspecialchars($article['link']) . '" class="icon-link">
Call to action
<svg class="bi" width="1em" height="1em"><use xlink:href="#chevron-right"></use></svg>
</a>
</div>';
}
?>通过这种方式,每轮循环都会真实读取当前 $article 的 title、description 和 link,确保三组 HTML 块分别展示不同内容,真正实现数据驱动的动态渲染。
上一篇:钉钉公告无法查看怎么处理
下一篇:Win10控制面板空白怎么解决?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9