我有一个包含照片文件路径、标题和它们出现的顺序等的对象。
我需要按照“顺序”对单张照片进行排序,这样当我遍历每张照片时,它们就会按照顺序值指定的顺序出现。
这是一个示例对象:
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] =>
)
最佳答案
像这样对数据库中的数据进行排序总是更好:
$photos = Photo::orderBy('order')->get();
这应该会给您带来更好的性能。
但是,如果上述方法不可行,您可以在您的收藏中调用以下方法:
$collection = $collection->sortBy('order');
这将根据您那里的任何模型的 order 字段对其进行升序排序。
如果您想按降序对它们进行排序,请执行以下操作:
$collection = $collection->sortBy('order', SORT_REGULAR, true);
关于php - 使用 php (laravel) 对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31701559/