Php 使用Elount在Laravel中实现Foreach循环的数组元素逆序
我有一个评分表,有不同的评分、字符串和单选按钮 现在我想循环这些。通常,我会这样着手解决:Php 使用Elount在Laravel中实现Foreach循环的数组元素逆序,php,arrays,laravel,eloquent,Php,Arrays,Laravel,Eloquent,我有一个评分表,有不同的评分、字符串和单选按钮 现在我想循环这些。通常,我会这样着手解决: <table> <tr> <th>ID</th> <th>Type</th> <th>Comment</th> </tr> @foreach($scores as $score) <tr>
<table>
<tr>
<th>ID</th>
<th>Type</th>
<th>Comment</th>
</tr>
@foreach($scores as $score)
<tr>
<td>{{$score->id}}</td>
<td>{{$score->ratingradio}}</td>
<td>{{$score->ratingtext}}</td>
</tr>
@endforeach
</table>
然后循环浏览$comments。但是我不仅想显示注释,我还想能够显示关于这个元素的所有信息。因此,最好像上面的方法一样,输出$score->ratingtext,$score->ratingradio,$score id,以及我想要的任何东西
我试着用
@foreach(array_reverse($scores) as $score)
这显然不起作用,因为$scores是一个对象,它需要一个数组。如何反向循环我的分数表中的每个分数?您可以使用:
array_reverse($scores->toArray());
或雄辩\收集方法来保留模型对象
$scores->reverse();
看看。看看API,似乎您可以使用
Take()
使其非常简单。在查询生成器和集合上运行时,它的行为稍有不同,因此您希望首先获取集合
$scores=Score::where('unit_id',$id)->where('created_at','>',Carbon::now()->subDays(3))->get()->take(-20)代码>检索最后20项非常容易
$scores = Score::where('unit_id', $id)
->where('created_at', '>', Carbon::now()->subDays(3))
->orderBy('created_at', 'desc')
->take(20)
->get();
$scores = $scores->reverse();
完成了
只需告诉它以相反的顺序取出与您的查询匹配的前20项,然后反转集合以获得正确的顺序。您也可以轻松地执行@foreach($scores->reverse()as$scores)
甚至还有最简单的方法:
$scores = Score::where('unit_id', $id)
->where('created_at', '>', Carbon::now()->subDays(3))
->orderBy('created_at', 'desc')
->orderBy('id', 'asc')
->take(20)
->get();
你为什么不简单地将排序规则设置为只取20行呢?为了清理它,$scores=Score::where('unit_id',$id)->where('created_at','>',Carbon::now()->subDays(3))->get()->reverse()->take(20)
应该可以工作。你到底是什么意思?上面的操作将完全按照它应该执行的操作。
$scores = Score::where('unit_id', $id)
->where('created_at', '>', Carbon::now()->subDays(3))
->orderBy('created_at', 'desc')
->orderBy('id', 'asc')
->take(20)
->get();