在Laravel中使用Eloquent的带有Foreach循环的数组元素的逆序 [英] Reverse Order of Array Elements with Foreach Loop using Eloquent in Laravel
问题描述
我有一个评分表,其中包含不同的评分,字符串和单选按钮。
I have a Score-Table with different ratings, strings and radio-buttons.
现在我想遍历这些。通常,我会像这样解决它:
Now I want to loop through these. Normally I would go about solving it like this:
<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>
但是我不仅希望颠倒顺序,而且还希望数组是切片,使其仅输出数组的最后20个元素。
But I don't only want the order to be reversed, but I also want the array to be sliced, so that it just outputs the last 20 Elements of the array.
我试图在控制器中像这样解决它:
I attempted solving it like this in my Controller:
$scores = Score::where('unit_id', $id)->where('created_at', '>', Carbon::now()->subDays(3))->get();
// Save all ratingtexts in an array
$comments = $scores->lists('ratingtext');
$commenttype = $scores->lists('ratingradio');
// Get the last 20 Elements of the Array
$comments = array_slice($comments, -20, 20, true);
// Reverse the array, to have the latest element first displayed
$comments = array_reverse($comments, true);
然后遍历$ comments。但我不仅要显示评论,还希望能够显示有关此元素的所有信息。因此,最好像上面所说的那样雄辩,我输出$ score-> ratingtext,$ score-> ratingradio,$ score-id以及我想要的任何内容。
And then looping through the $comments. But I don't only want to display the comment, I also want to be able to display all Information regarding this Element. So preferably like the above method with eloquent, where I output $score->ratingtext, $score->ratingradio, $score-id, and whatever I want.
I尝试只使用
@foreach(array_reverse($scores) as $score)
显然这没有用,因为$ scores是一个对象,并且它期望一个数组。
Which obviously didn't work, because $scores is an object and it was expecting an array. How am I going to reverse loop through every score of my Scores Table?
推荐答案
检索最后20个项目非常容易。 / p>
Retrieving the last 20 items is quite easy.
$scores = Score::where('unit_id', $id)
->where('created_at', '>', Carbon::now()->subDays(3))
->orderBy('created_at', 'desc')
->take(20)
->get();
$scores = $scores->reverse();
完成。
只要告诉它
以相反的顺序提取与查询匹配的前20个项目,然后反转集合以获得正确的顺序。
Just tell it to pull out the first 20 items that match your query, with a reversed order and then reverse the collection to get the proper order.
这篇关于在Laravel中使用Eloquent的带有Foreach循环的数组元素的逆序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!