Collection of varieties laravel and then keyed

I am making a raking system for my users, and here is what I still have:

Get all users and sort them by points - it works great.

$users = User::all(); $users = $users->sortByDesc(function($item){ return $item->points()->sum('amount'); }); 

Find your position in the ranking - it works great

 $position = 0; foreach($users as $user){ if(Auth::user()->id == $user->id) break; $position++; } 

Get yourself and users above / below me - this will not work. I get random users. It looks like the collection is no longer sorted.

 $myRank = new Collection(); if($position > 9){ $myRank->add($users->get($position-1)); $myRank->add($users->get($position)); $myRank->add($users->get($position+1)); return view('rank.show', ['topTen' => $users->take(15), 'myRank' => $myRank]); } 

Please help me with this or give some hint on a different approach (light weight for many entries)

+5
source share
3 answers

I think the problem is this:

When you call User::all() , you get something like this:

 0 => points: 10 1 => points: 50 2 => points: 30 3 => points: 70 4 => points: 20 

Then you use the sortBy function, which reorders the collection, but does not reset the keys. So you get something like this:

 3 => points: 70 1 => points: 50 2 => points: 30 4 => points: 20 0 => points: 10 

Thus, the use of position -1, position and position +1 does not make sense here.

What you can do is use the values ​​() function, which will reset the keys of your collection:

 0 => points: 70 1 => points: 50 2 => points: 30 3 => points: 20 4 => points: 10 

So, I think the following code will work.

 $users = User::all(); $users = $users->sortByDesc(function($item){ return $item->points()->sum('amount'); })->values(); 

And then get 3 users from positions - 1 to position + 1:

 $myRank = $users->splice($position - 1, 3); 
+10
source

To sort by key, you can get an array of support, and then create a collection again.

  $c = collect(['a' => 1, 'c' => 67, 'b' => 2]); $items = $c->all(); ksort($items); $c = collect($items); 

Or you can use a macro to access the support array.

  Collection::macro('ksort', function(){ //macros callbacks are bound to collection so we can safely access // protected Collection::items ksort($this->items); return $this; }); 

The latter solution can be very useful if you need to sort collections by keywords in many places in the code base

+5
source

For any sorting of array by key I would suggest my own PHP function ksort () .

0
source

All Articles