使用 php (laravel) 对对象进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31701559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting an object with php (laravel)
提问by TEster
I have an object which contains photo file paths,there caption and the order they apear in etc.
我有一个对象,其中包含照片文件路径、标题和它们出现的顺序等。
I need to sort the individual photos in order of the 'order', So that when i loop through each of the photos, they appear in the order specified by the order value.
我需要按照“顺序”的顺序对单张照片进行排序,这样当我遍历每张照片时,它们就会按照顺序值指定的顺序出现。
Here is an example object:
这是一个示例对象:
object: Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => Photo Object
(
[timestamps] =>
[guarded:protected] => Array
(
[0] => id
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[id] => 11
[res_id] => 1
[order] => 6
[owner_type] => Hotel
[owner_id] => 1
[gallery] =>
[caption] =>
[file] => Hotel_1_11.jpg
[deleted_at] =>
)
回答by jedrzej.kurylo
It's always better to sort data in the database, like that:
对数据库中的数据进行排序总是更好,如下所示:
$photos = Photo::orderBy('order')->get();
This should give you better performance.
这应该会给你更好的性能。
However, if above is not possible, you can call the following on your collection:
但是,如果以上不可能,您可以在您的收藏中调用以下内容:
$collection = $collection->sortBy('order');
This will sort it in ascending order by the orderfield of whatever models you have there.
这将按照您在那里拥有的任何模型的order字段按升序对其进行排序。
In case you want to sort them in descending order, do:
如果您想按降序对它们进行排序,请执行以下操作:
$collection = $collection->sortBy('order', SORT_REGULAR, true);
回答by RW24
Since Laravel 5.1 you can use a rather shorter syntax to order in descendingorder:
从 Laravel 5.1 开始,您可以使用更短的语法按降序排序:
$collection = $collection->sortByDesc('order');
Instead of:
代替:
$collection = $collection->sortBy('order', SORT_REGULAR, true);
回答by Shahrukh Anwar
If you have a collection, and you want to sort it on basis of any of it's key, then you can use the following piece of code.
如果您有一个集合,并且想根据它的任何一个键对其进行排序,那么您可以使用以下代码段。
//if you want to sort in ascending order
$unique = $collection->unique()->sortBy('YOUR_KEY_TO_SORT');
//if you want to sort in descending order
$unique = $collection->unique()->sortBy('YOUR_KEY_TO_SORT', SORT_REGULAR, true);