欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Collection reverse method not reversing 反传 倒序 逆转 倒过来排序 重置键 重置key 有大用

下面两步自己亲自做的  有大用

1) 反转  $collection= $collection->reverse(); (此时键不反转)

2)重置键  $collection = $collection->values();



I'm trying to reverse the collection items, but It's not returning correct output.

Here's the code I have tried for testing:

$collection = collect([1, 2, 3, 4, 5]);
$reversed = $collection->reverse();
$reversed->all();

And the response should be this:

[5, 4, 3, 2, 1]

But I'm receiving this as response:

array:5 [▼
  4 => 5
  3 => 4
  2 => 3
  1 => 2
  0 => 1
]

来自 https://laracasts.com/discuss/channels/laravel/collection-reverse-method-not-reversing


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>

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);

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 tried just using

 @foreach(array_reverse($scores) as $score)

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?

    5 Answers 正确答案 但是 它不重置键(键也跟着倒过来了) (下面标红的有重置键的功能)

    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();

    Done.

    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.

      You can use:

      array_reverse($scores->toArray());

      or Eloquent\Collection methods to keep the Model object

      $scores->reverse();

      Take a look at the Eloquent\Collection API.

        You can as well easily do @foreach($scores->reverse() as $score)

        Looking through the API, it seems you can use take() to make this very simple. It behaves a little differently when running on query builder vs collection, so you'd want to get your collection first.

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

        There are even easyest way:

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

        来自  https://stackoverflow.com/questions/23463663/reverse-order-of-array-elements-with-foreach-loop-using-eloquent-in-laravel?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa


        I use filter method from Collection class to remove some objects from collection. But after that operation, sometimes objects with keys eg. 1, 4, 5 left. I would like to always have elements with order 0, 1, 2, 3 etc. after filter action.

        Is there any elegant way to do it without rewriting table to a new one?

        Thanks!

          1 Answer (正确答案下面这个应该是重置键重设键的功能)

          You can use Laravel Collection's values() method to make the the keys of a collection in a serialized order like this:

          // Just for demonstration
          $collection = collect([
              10 => ['fruit' => 'Apple', 'price' => 200],
              11 => ['fruit' => 'Mango', 'price' => 500]
          ]);
          
          $values = $collection->values();
          
          $values->all();
          
          /* Result would be:
              [
                  0 => ['fruit' => 'Apple', 'price' => 200],
                  1 => ['fruit' => 'Mango', 'price' => 500],
              ]
          */

          Hope this helps!

          Collection: allow $preserve_keys option on reverse() #9948


          Is there a reason the Collection's reverse method doesn't have a $preserve_keys option (see PHP Docs for array_reverse)? Is it simply a PHP version issue?

          I ended up having to use collect(array_reverse($points->all(), true)) instead of what I hoped would just be $points->reverse(true).

          @cabloo

          Wow, thanks @arrilot - that was fast.


          来自  https://github.com/laravel/framework/issues/9948


          普通分类: