对于laravel中的每个循环?

时间:2014-02-13 13:54:33

标签: laravel laravel-4

我试图在同一视图上循环浏览不同的数据,有时数据看起来像这样:

[{"id":"3","title":"Collection C","short_title":"CC","looks":[{"id":"6","title":"Look 6","image":null,"sell":null,"description":null,"sort":null,"published":"1","pivot":{"collection_id":"3","look_id":"6"}},{"id":"7","title":"Look 7","image":null,"sell":null,"description":null,"sort":"1","published":"1","pivot":{"collection_id":"3","look_id":"7"}}]},{"id":"1","title":"Collection A","short_title":"CA","looks":[{"id":"2","title":"Look 2","image":null,"sell":null,"description":null,"sort":"0","published":"1","pivot":{"collection_id":"1","look_id":"2"}}]}]

有时它看起来像这样:

{"id":"1","title":"Collection A","thumb":null,"banner":null,"video":"ftfgf","looks":[{"id":"2","title":"Look 2","image":null,"sell":null,"description":null,"sort":"0","published":"1","url":"test","pivot":{"collection_id":"1","look_id":"2"}}]} BESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswyBESbswy

我通过以下方式将其循环:

@foreach($data as $show)
{{ $show->title }}
@endforeach

第二组数据打破了我的循环,这是因为它不在数组本身,如果是这样,我怎么能把它放到一个数组中,因此它是唯一的元素。

或者有更好的方法来解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

这是因为您使用的是对象而不是数组。

您应该问自己的一件事是,为什么最终会出现$data可能是对象或数组的情况?

在我看来,你的代码应该更强大。如果你知道你在foreach上做了$data,那么你应该强制它总是一个数组,否则你将会陷入一团糟。

如果您无法更改来源,可以在foreach

之前执行此类操作
<?php if(!is_array($data)) $data[] = $data; ?>

或者,正如您所说,在输出

之前,您应该在模型上使用->toArray()

您可以(我认为)在您的雄辩查询中使用->get()而不是->first()。我认为->get()总是输出一个数组。

只要您确定$data始终是数组,那么您应该没问题。

更新根据您的评论

这样做是为了确保您输出数组

$data = $this->with(array('looks' => function($query){ $query->wherePublished(1)->orderBy('sort')->take(3)->skip(0); }))->get($id, array('id', 'title', 'thumb', 'banner', 'video'));  

if(is_array($data))
{
  return $data;
}

return array($data);

答案 1 :(得分:0)

在开始循环之前我会做一些检查,看看它是第一种数据还是第二种。

@if (is_array($data))
    @foreach($data as $show)
    {{ $show->title }}
    @endforeach
@else
    {{-handle it as an object-}}
@endif