Home  >  Article  >  Backend Development  >  Laravel框架illuminatesupportcollection排序问题

Laravel框架illuminatesupportcollection排序问题

WBOY
WBOYOriginal
2016-06-20 12:37:10957browse

Laravel框架illuminate\support\collection排序问题技术

maybe yes 发表于2015-04-03 00:59

Laravel 的 Collection 的排序有个问题,前几天折腾了好久,一直怀疑是自己代码有问题。Collection 对象执行 sort 后需要执行 values 方法,否则 Collection 对象的 items 排序结果没有生效。当然手动的 toArray() 是生效的。查看 Collection sort 方法内部实现是调用了 PHP 的 uasort 函数,该函数排序后会维持原来的 key => value 关系。

官方文档截取如下:

Collection values()Reset the keys on the underlying array.Return ValueCollection

一直弄不明白,为什么这个方法叫 values,这个取名真让人费解,values 方法内部使用 array_values 方法对 items 进行了重新赋值。有时候,开发特别折腾,一直在更改... 代码片段如下,需要调用 values 方法使得排序生效。

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

开发过程中特别的挑刺,过分的在乎变量命名和参数方式,过早的优化代码,都是不好的。这个世界上应该没有哪两家的公司的业务是完全一样的,用了太多的开源软件也不一定是好事。顺便评价下 Laravel,传说中的 Artisan,我感觉用起来很不舒畅,错误日志不打印日期,不打印哪里出错,叫人怎么调试。

sort 方法 和 values 方法内部实现代码:

public function sort(Closure $callback){    uasort($this->items, $callback);    return $this;}public function values(){    $this->items = array_values($this->items);    return $this;}

阅(498)评(0)查看评论


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn