php - for循环中的索引不返回最后一个索引
问题描述
我有一个图片库,每个都由索引保存.. gallery1: /image here.. gallery2: / image here.. etc.. 我使用具有多个 for 循环的索引来返回图像并按列返回,因为它要么砖石或矩形。除了最后一个索引外,我的回报很好。
private function rectangle($items, $columns, $contents = array()) {
$thumbs = array('talent_thumbnail','360x207');
$arr = array();
$col = round(count($items) / $columns);
$perCol = floor(count($items) / $columns);
$extra = count($items) % $columns;
$ind = 1;
$length = count($items);
$arr = array();
for($i = 0; $i < $columns && $ind < $length; $i++) {
$temp = array();
for($j = 0; $j < $perCol; $j++) {
$obj = new JObject();
$obj->image = $items['gallery' . $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
}
if ($extra > 0) {
$obj = new JObject();
$obj->image = $items['gallery'. $ind]['photo'];
$obj->alt_text = $items['gallery'. $ind]['alt_text'];
$temp[] = $obj;
$ind++;
$extra--;
}
$arr[] = $temp;
}
}
我知道这不会那么难,但我还没有那么擅长。非常欢迎任何帮助。谢谢你。
解决方案
您将变量设置$ind
为 1,计算数组的长度,然后使用条件初始化 for 循环$ind < $length
。
当$ind
达到访问最后一项所需的索引时,循环不会再次运行,因为$ind
现在等于$length
,而不是更小。
您可以通过将 for 循环中的条件更改为“小于或等于”来解决此问题:
$i < $columns && $ind <= $length
$ind
当到达最后一个索引
时,这将再次运行循环。
推荐阅读
- html - 未处理嵌套 div 中的 Markdown
- java - Java 无法解析的日期 SimpleDateFormat
- javascript - 从 laravel balde 获取 foreach 循环的值并将其传递给 javascript 函数
- itext - 我们可以使用最新的 iText jar 在文档中添加多行文本水印吗?
- java - MimeMessage 不能使用内部类
- tensorflow.js - 是否需要 Python 运行时才能使用 Tensorflow.js 节点?
- node.js - NodeJS:aws-sdk sts.assumeRole 不工作
- wordpress - WooCommerce 查询所有产品
- jenkins - 如何使用 env 变量来锁定声明性管道中的多个阶段
- python - Python - 如何找到下一个最大日期