【发布时间】:2014-06-21 05:38:09
【问题描述】:
我有一个包含不同评分、字符串和单选按钮的评分表。
现在我想遍历这些。通常我会这样解决它:
<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 个元素。
我尝试在我的控制器中这样解决它:
$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);
然后循环遍历 $cmets。但我不仅想显示评论,还希望能够显示有关此元素的所有信息。所以最好像上面带有 eloquent 的方法,我输出 $score->ratingtext、$score->ratingradio、$score-id 以及任何我想要的。
我尝试过使用
@foreach(array_reverse($scores) as $score)
这显然不起作用,因为 $scores 是一个对象,它期待一个数组。我将如何反向循环遍历我的分数表的每个分数?
【问题讨论】:
-
为什么不简单地将
orderBy和limit设置为只获取20 行?
标签: php arrays laravel eloquent