代码之家  ›  专栏  ›  技术社区  ›  ifusion

循环时如何仅设置偏移?

  •  2
  • ifusion  · 技术社区  · 7 年前

    // This shows the first 6 images
    
    <% loop $GalleryImages.Limit(6) %>
    
        <img src="$Image">
    
    <% end_loop %>
    

    然后我需要从病房的第7张图片中显示。我们可以在这里使用偏移量,但必须设置一个限制(第一个参数)

    <% loop $GalleryImages.Limit(100, 6) %>
    
        <img src="$Image">
    
    <% end_loop %>
    

    有没有办法只设置偏移量,或者我应该用另一种方法来解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  5
  •   UncleCheese    7 年前

    最干净的做法是在控制器或模型中创建一个运行查询的方法。

    public function OtherGalleryImages()
    {
      return $this->GalleryImages()->limit(null, 6);
    }
    

    但我想问一下,你是否真的想运行一个无限制的查询,出于这个原因,我认为一个更简单的解决方法是在你的查询中添加一个合理的数字 limit

        2
  •  -3
  •   BenG    7 年前

    PHP的 array_slice 方法允许您指定开始,而不知道数组的长度。 http://php.net/manual/en/function.array-slice.php

    使用切片的优点是,如果数组太短或太长,它将返回一个空数组而不是null,从而避免错误