Laravel framework illuminatesupportcollection sorting problems Laravel framework illuminate \ support \ collection sorting problems
Maybe yes, published on
There is a problem with the sorting of Laravel collections. I have been tossing around for a long time a few days ago and I have always suspected that my code is faulty. The values method must be executed after the Collection object executes sort. Otherwise, the items sorting result of the Collection object does not take effect. Of course, manual toArray () takes effect. The internal implementation of the Collection sort method is to call the uasort function of PHP, which maintains the original key => value relationship after sorting.
The official documents are as follows:
Collection values()Reset the keys on the underlying array.Return ValueCollection
I still don't understand why this method is called values. this name is really confusing. the values method uses the array_values method to re-assign values to items. Sometimes, the development is particularly difficult, and the code snippets are constantly being modified as follows. you need to call the values method to make the sorting take effect.
$left = $right = null;switch($sortby){ case "rating": case "month_sales": $left = -1; $right = 1; break; case "order_lead_time": case "minimum_order_amount": $left = 1; $right = -1; break;}if($ascending === "1"){ $left = 1; $right = -1;}elseif($ascending === "0"){ $left = -1; $right = 1;}$restaurants->sort(function($a, $b) use ($sortby, $left, $right){ return ($a->{$sortby} >= $b->{$sortby}) ? $left : $right;});$restaurants->values();
In the development process, it is very difficult to optimize the code too early due to variable naming and parameter methods. No two companies in the world have the same business. it is not necessarily a good thing to use too many open-source software. By the way, Laravel, the legendary Artisan, seems quite uncomfortable to use. the error log does not print the date or print any errors. how can this problem be debugged.
Internal Implementation code of the sort and values methods:
public function sort(Closure $callback){ uasort($this->items, $callback); return $this;}public function values(){ $this->items = array_values($this->items); return $this;}
Read (498) Comments (0) View Comments