使用Laravel中的Eloquent使用Foreach循环反转数组元素

Lov*_*ess 2 php arrays laravel eloquent

我有一个得分表,有不同的评级,字符串和单选按钮.

现在我想循环这些.通常我会像这样解决它:

 <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>
Run Code Online (Sandbox Code Playgroud)

但是我不仅希望颠倒顺序,而且还希望对数组进行切片,以便它只输出数组的最后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);
Run Code Online (Sandbox Code Playgroud)

然后循环遍历$ comments.但我不仅要显示评论,我还希望能够显示有关此元素的所有信息.所以最好像上面的方法一样雄辩,我输出$ score-> ratingtext,$ score-> ratingradio,$ score-id,以及我想要的任何东西.

我试过用

 @foreach(array_reverse($scores) as $score)
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为$ score是一个对象,它期待一个数组.我如何在我的得分表的每个分数中反向循环?

oll*_*ead 19

检索最后20个项目非常简单.

$scores = Score::where('unit_id', $id)
    ->where('created_at', '>', Carbon::now()->subDays(3))
    ->orderBy('created_at', 'desc')
    ->take(20)
    ->get();

$scores = $scores->reverse();
Run Code Online (Sandbox Code Playgroud)

完成.

只需告诉它提取与您的查询匹配的前20个项目,颠倒顺序然后反转集合以获得正确的顺序.


小智 15

你也可以轻松做到 @foreach($scores->reverse() as $score)


Aur*_*rel 5

您可以使用:

array_reverse($scores->toArray());
Run Code Online (Sandbox Code Playgroud)

或Eloquent \ Collection方法来保留Model对象

$scores->reverse();
Run Code Online (Sandbox Code Playgroud)

看一看Eloquent \ Collection API