显示数组中的特定值 - Laravel

时间:2017-02-13 15:03:00

标签: arrays laravel distinct-values

我正在尝试找到一种从数组中显示特定值的简单方法。这是项目中的一些背景知识,以及我正在努力实现的目标。

背景

我转储了这个数组{{ dd($stories) }}

Collection {#240 ▼
  #items: array:7 [▼
    0 => Story {#241 ▼
      #table: "stories"
      #fillable: array:7 [▶]
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▼
        "id" => 17
        "title" => "Some New Post"
        "slug" => "some-new-post"
        "category_id" => 8
        "is_draft" => 0
        "feat_image" => null
        "body" => """
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas non sagittis ipsum. Vivamus tristique, purus ut accumsan blandit, lorem turpis pellentesque ▶
          <p>Nulla nec dignissim odio. Curabitur sodales ullamcorper sapien ac tristique. Ut condimentum sodales sem, in pretium felis efficitur quis. Proin rhoncus a ips ▶
          <p>Nulla facilisi. Suspendisse nec nisl tristique, consectetur nibh et, sollicitudin ligula. Aliquam erat volutpat. Nunc et mauris vehicula nibh rutrum viverra. ▶
          <p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In hac habitasse platea dictumst. Nulla auctor massa faucibus elit semp ▶
          <p>Maecenas congue mi sapien, eu dictum elit vestibulum quis. Aenean scelerisque iaculis turpis, sed dictum nisi lobortis at. Quisque justo ante, dapibus vel ia ▶
          """
        "excerpt" => "Some excerpt for all to see"
        "created_at" => "2017-02-12 23:00:35"
        "updated_at" => "2017-02-12 23:00:35"
      ]
      #original: array:10 [▶]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => Story {#242 ▶}
    2 => Story {#243 ▶}
    3 => Story {#244 ▶}
    4 => Story {#245 ▶}
    5 => Story {#246 ▶}
    6 => Story {#247 ▶}
  ]
}

我能够设置sql查询以使用eloquent获取'is_draft' = 0的前七(7)项:

 $content['stories'] = Story::where('is_draft', '=', 0)
            ->orderBy('created_at', 'desc')
            ->take(7)
            ->get();

现在的问题是,我想静态输出这个数组的数据。例如:

<span class="grid single">{{ $story[0]->title }}</span>
<span class="grid double">{{ $story[1]->title }}</span>

应输出

<span>Some New Post</span>
<span>Another Post</span>

我不确定语法是什么或如何设置数组循环并仅显示请求的项目。我确定它必须要求foreach循环,并且可能需要嵌套while循环。只是不确定语法。任何想法的家伙?

1 个答案:

答案 0 :(得分:0)

如果您已经拥有正确的项目列表(在本例中我称之为$stories),您只需使用Laravel Blade的@foreach指令循环遍历该列表:

@foreach ($stories as $story)
<span>{{ $story->title }}</span>
@endforeach