有几种不同的方式对集合进行排序。
该sort方法对集合进行排序:
$collection = collect([5, 3, 1, 2, 4]); $sorted = $collection->sort(); echo $sorted->values()->all(); returns : [1, 2, 3, 4, 5]
该sort方法还允许使用您自己的算法传递自定义回调。在幕后排序使用php的usort。
$collection = $collection->sort(function ($a, $b) { if ($a == $b) { return 0; } return ($a < $b) ? -1 : 1; });
该sortBy方法按给定键对集合进行排序:
$collection = collect([ ['name' => 'Desk', 'price' => 200], ['name' => 'Chair', 'price' => 100], ['name' => 'Bookcase', 'price' => 150], ]); $sorted = $collection->sortBy('price'); echo $sorted->values()->all(); returns: [ ['name' => 'Chair', 'price' => 100], ['name' => 'Bookcase', 'price' => 150], ['name' => 'Desk', 'price' => 200], ]
该sortBy方法允许使用点表示法格式来访问更深的键,以便对多维数组进行排序。
$collection = collect([ ["id"=>1,"product"=>['name' => 'Desk', 'price' => 200]], ["id"=>2, "product"=>['name' => 'Chair', 'price' => 100]], ["id"=>3, "product"=>['name' => 'Bookcase', 'price' => 150]], ]); $sorted = $collection->sortBy("product.price")->toArray(); return: [ ["id"=>2, "product"=>['name' => 'Chair', 'price' => 100]], ["id"=>3, "product"=>['name' => 'Bookcase', 'price' => 150]], ["id"=>1,"product"=>['name' => 'Desk', 'price' => 200]], ]
此方法与该方法具有相同的签名sortBy,但是将以相反的顺序对集合进行排序。