用php(laravel)对对象排序

TEs*_*ter 1 php laravel eloquent laravel-5

我有一个对象,其中包含照片文件路径,标题和它们的顺序等.

我需要按照"订单"的顺序对单张照片进行排序,这样当我遍历每张照片时,它们会按照订单值指定的顺序显示.

这是一个示例对象:

    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] => 
                        )

Run Code Online (Sandbox Code Playgroud)

([items:protected] => Array([0] => Photo Object([timestamps] => [guarded:protected] => Array([0] => id)

    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] => 
                        )

Run Code Online (Sandbox Code Playgroud)

jed*_*ylo 5

在数据库中对数据进行排序总是更好,例如:

$photos = Photo::orderBy('order')->get();
Run Code Online (Sandbox Code Playgroud)

这应该会给你更好的表现.

但是,如果无法满足以上条件,您可以在您的收藏中调用以下内容:

$collection = $collection->sortBy('order');
Run Code Online (Sandbox Code Playgroud)

这将按照您所拥有的任何模型的顺序字段按升序对其进行排序.

如果您想按降序对它们进行排序,请执行以下操作:

$collection = $collection->sortBy('order', SORT_REGULAR, true);
Run Code Online (Sandbox Code Playgroud)