gpt4 book ai didi

php - 在 PHP 中使用 div 标签动态创建网格布局

转载 作者:行者123 更新时间:2023-11-27 23:03:35 25 4
gpt4 key购买 nike

所以我有一个类似的问题one但我只在 vanilla PHP 中而不是在 wordpress 中应用它。经过无数小时的努力,我终于得到了答案,但不知何故,如果我增加网格数的大小,项目就不会对齐。

我希望它看起来像这样:

-----------
- 1 2 3 4 -
-----------

但是:如我的问题所述,如果我尝试增加网格(或更准确地说是项目),它会变成这样:

-----------
- 1 2 3 4 -
- 5 -
-6 -
-7 -
-----------

它变得杂乱无章。下面是我尝试试验的代码。

<div class="container">
<?php
$i=0;
$item=0;
$html_tag = '<div class = "row"><div class="col 3">';

while($item <= 4)
{
?>
<?php if($i % 4 == 0) {
$html_tag .= 'col '.$i.'</div>';
}
else {
$html_tag .= '<div class="col"> col '.$i.'</div>';
}
?>
<?php
$i++;
$item++;
}
$html_tag .= '</div>';
?>

<?php echo $html_tag ?>

附言我正在使用 twitter bootstrap 4 因为它的响应能力。

编辑:

请注意下面的屏幕截图,我刚刚意识到在 div 行中有一个额外的文本 'col ?3' 而不是另一个 div 列(未创建)。

enter image description here

最佳答案

你应该检查你的代码,最终的结构不正确。

这是你得到的

<div class="container">
<div class="row">
<div class="col 3">col 0</div>
<div class="col"> col 1</div>
<div class="col"> col 2</div>
<div class="col"> col 3</div>
col 4
</div>
</div>

试试这个代码

$html = '';
$totalItemPerLine = 3;
$totalItem = 7;
for($i = 0; $i < $totalItem; $i++)
{
if($i % $totalItemPerLine == 0)
{
$html .= '<div class="row">'; // OPEN ROW
}

$html .= '<div class="col"> col '.$i.'</div>';

if($i % $totalItemPerLine == ($totalItemPerLine-1))
{
$html .= '</div>'; // CLOSE ROW
}
}

echo $html;

注意:您可以使用 while 执行完全相同的操作,但为了可读性,我使用了 for

编辑:

根据@DavidDiaz 的评论,这是直接使用 HTML 的代码但我建议你学习 POO 并使用类来完成此页面

$html = '';
$totalItemPerLine = 3;
$totalItem = 7;
for($i = 0; $i < $totalItem; $i++)
{
if($i % $totalItemPerLine == 0)
{?>
<div class="row"> <!-- OPEN ROW -->
<?php } ?>

<div class="col"> col <?= $i ?> </div>

<?php if($i % $totalItemPerLine == ($totalItemPerLine-1))
{ ?>
</div> <!-- CLOSE ROW -->
<?php }
} ?>

关于php - 在 PHP 中使用 div 标签动态创建网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51136821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com