提问人:Ashley Serrano-Ziel 提问时间:8/4/2022 更新时间:8/4/2022 访问量:88
如何将PHP循环插入PHP创建的div中?
How to insert PHP loop into a div that was created by PHP?
问:
我已经遍历了 6 次$elements,为公司提供的每项服务创建了 6 个相同的容器。我正在尝试将“if while”循环放在 $element 4 'overlay' div 内的 php 底部。“if while”循环从 MySQL 数据库调用服务标题并将其显示在网页上。我试过将 php 代码直接粘贴到 div 标签之间,我试过将其留在原处,我试过将“if while”循环放在它自己的文件中,并将 include 语句放在“overlay”div 标签之间。没有任何效果。通过之前的尝试,我已经能够让 h3 标签填充在 DOM 中的错误位置,但由于某种原因我无法将它们放在我想要的位置。您能告诉我如何让“if while”循环的输出显示在“overlay”div 中吗?
$element = "<div class='service'>";
$element2= "<div class='img_container'>";
$element3= "<img class='service_img'/></div>";
$element4= "<div class='overlay'></div>";
$element5= "<div class='service_details'></div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element, $element2, $element3, $element4, $element5;
}
?>
<?php
if($resultCheck > 0){
while($row = $result->fetch_assoc()){
echo "<h3 class='service_title'>" . $row['service_title'] . "<br>" . "</h3>";
}}
?>
答:
1赞
Rylee
8/4/2022
#1
请参阅下面的进一步重构
若要在 EACH 服务上包含该 foreach 循环,可以将代码调整为如下所示:
<?php
$element = "<div class='service'>";
$element2 = "<div class='img_container'>";
$element3 = "<img class='service_img'/></div>";
$element4 = "<div class='overlay'></div>";
$element5 = "<div class='service_details'></div></div>";
$count = 6;
// this will end up with the title BEFORE the service element
// <h3 class="service-title">...</h3>
// <div class="service">...</div>
?>
<div class="container">
<?php if ($resultCheck > 0) {
while ($row = $result->fetch_assoc()) {
echo "<h3 class='service_title'>" . $row['service_title'] . "<br>" . "</h3>";
// the below loop is going to create 5 `<div class="service">...</div>`
// for EACH $row
foreach (range(1, $count) as $item) {
echo $element, $element2, $element3, $element4, $element5;
}
// you may want to instead want to echo directly
// echo $element, $element2, $element3, $element4, $element5;
}
} ?>
</div>
<?php
// ... rest of code
重构
通过阅读您的描述,我认为您追求的是更像这样的东西:
<?php
// refactored
// this format will include the title INSIDE the service element
// <div class="service">
// <h3 class="service-title">...</h3>
// ...
// </div>
?>
<div class="container">
<?php if ($resultCheck > 0) {
while ($row = $result->fetch_assoc()) { ?>
<div class="service">
<h3 class="service_title"><?php echo $row["service_title"]; ?></h3>
<div class="img_container">
<img class="service_img" />
</div>
<div class="overlay"></div>
<div class="service_details"></div>
</div>
<?php }
} ?>
</div>
<?php
// ... rest of code
评论
echo $element, $element2, $element3, $element4, $element5;