【问题标题】:Reverse Order of Array Elements with Foreach Loop using Eloquent in Laravel在 Laravel 中使用 Eloquent 使用 Foreach 循环反转数组元素的顺序
【发布时间】: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 是一个对象,它期待一个数组。我将如何反向循环遍历我的分数表的每个分数?

【问题讨论】:

  • 为什么不简单地将orderBylimit 设置为只获取20 行?

标签: php arrays laravel eloquent


【解决方案1】:

你可以使用:

array_reverse($scores->toArray());

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

$scores->reverse();

看看Eloquent\Collection API

【讨论】:

  • 要清除它,$scores = Score::where('unit_id', $id)-&gt;where('created_at', '&gt;', Carbon::now()-&gt;subDays(3))-&gt;get()-&gt;reverse()-&gt;take(20) 应该可以工作。
【解决方案2】:

查看API,您似乎可以使用take() 使这变得非常简单。在查询构建器与集合上运行时,它的行为略有不同,因此您需要先获取您的集合。

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

【讨论】:

    【解决方案3】:

    检索最后 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 个项目,然后反转集合以获得正确的顺序。

    【讨论】:

    • 你到底是什么意思?以上将完全按照它应该做的。
    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      还有最简单的方法:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 2016-07-06
        • 1970-01-01
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        相关资源
        最近更新 更多