php - 如何在 PHP 中循环网格
问题描述
<?php foreach($posts as $post) : ?>
<div class="col-md-4">
<h3><?php echo $post['title']; ?></h3>
<small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small>
</div>
<?php endforeach; ?>
我遇到的问题是每次循环都是相同的结果
如下图: 在此处输入图片描述
我的问题是否可以帮助我提供一个比我的更好的 PHP 循环,并且在任何给定的图像数量上都不会留下任何语法错误?
解决方案
我已经修改了您的代码,看起来很多,但那是因为我必须创建一个数组来模拟您收到的数据。
//create an array that contains the column sizes we want in order
<?php $gridLayoutConfig = array("col-md-12", "col-md-8", "col-md-4", "col-md-3", "col-md-3", "col-md-3"); ?>
//here I am simulating data since I dont have your data
<?php $posts = array(
array("title" => "Mean Streets", "name" => "Meaner Streets", "created_at" => "0000"),
array("title" => "Mean Streets 2", "name" => "Meaner Streets 2" , "created_at" => "0000"),
array("title" => "Mean Streets 3", "name" => "Meaner Streets 3", "created_at" => "0000"),
array("title" => "Mean Streets 4", "name" => "Meaner Streets 4", "created_at" => "0000"),
array("title" => "Mean Streets 5", "name" => "Meaner Streets 5", "created_at" => "0000"),
array("title" => "Mean Streets 6", "name" => "Meaner Streets 6", "created_at" => "0000")
); ?>
<?php $i = 0; ?>
//create container row outside the foreach
<?php echo "<div class='row'>"; ?>
<?php foreach($posts as $post) : ?>
//set divs class to whatever count is currently (0 = "col-md-12", 1 = "col-md-8")
//divide count by how many entries in our gridLayoutConfig by whatever $i that means when we reach the last array entry $i % count($gridLayoutConfig) roll back around to equal 0 starting the layout again.
<?php echo '<div class="'.$gridLayoutConfig[$i % count($gridLayoutConfig)].'">' ?>
<h3><?php echo $post['title']; ?></h3>
<small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong>
<?php echo $post['name']; ?></strong></small>
</div>
<?php $i++; ?>
<?php endforeach; ?>
<?php echo "</div>"; ?>
还添加了一个 PHPFiddle 以更好地演示打开链接按 F9 运行然后检查检查器,您将看到每个 div 都有正确的类,它不会在小提琴中正确显示,因为没有包含引导程序,但应该在您自己的页面中正常工作.
http://phpfiddle.org/main/code/aei9-tw86
当我们到达“Mean Streets 7”时,您会在 php fiddle 中看到 $gridLayoutConfig 再次从开头 ($gridLayoutConfig[0]) 开始,并将重复该模式。
推荐阅读
- scala - 在 Spark 中将数据框列转换为向量
- json - 无法在 curl 命令上将正文读取为 JSON 对象
- xml - 提交 xml 下拉结果
- android - 错误:资源“attr/actionBarSize”的重复值与配置“”
- node.js - Passport js 密码重置使用 Express 和 Mongo
- sql - SQL Server 为每个修改的列创建审核
- sql - 查询 JSONB[] postgres
- html - CSS 网格模板列重复不超过 X 次
- html - 浏览器之间的 SVG 不一致
- node.js - NPM Install 无法安装所有模块并且中途挂起