首页 > 解决方案 > 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;
    }
}

我知道这不会那么难,但我还没有那么擅长。非常欢迎任何帮助。谢谢你。

标签: php

解决方案


您将变量设置$ind为 1,计算数组的长度,然后使用条件初始化 for 循环$ind < $length
$ind达到访问最后一项所需的索引时,循环不会再次运行,因为$ind现在等于$length,而不是更小。

您可以通过将 for 循环中的条件更改为“小于或等于”来解决此问题:

$i < $columns && $ind <= $length
$ind当到达最后一个索引 时,这将再次运行循环。


推荐阅读