简体   繁体   中英

How to sort collection by array?

How to sort given collection

Collection {
    #items: array:3 [
        0   => MenuPosition,    // ->label = "About Us"
        1   => MenuPosition,    // ->label = "Homepage"
        2   => MenuPosition     // ->label = "Shop"
    ]
}

with help of this array

$correctOrder = [
    'Homepage',
    'Shop',
    'About Us'
];

So in the end i will get

Collection {
#items: array:3 [
    0   => MenuPosition,    // ->label = "Homepage"
    1   => MenuPosition,    // ->label = "Shop"
    2   => MenuPosition     // ->label = "About Us"
]

MenuPosition is an instance of Eloquent's model

edit

You can achieve this using combine() . From the docs:

The combine method combines the keys of the collection with the values of another array or collection

So take the indices as the keys from the $correctOrder array and map the Collection against those.

https://laravel.com/docs/5.4/collections#method-combine

Assuming that $collection holds the menu items, try this one:

$collection = 
    /*
    Collection {
        #items: array:3 [
            0   => MenuPosition,
            1   => MenuPosition,
            2   => MenuPosition
        ]
    }
    */

$correctOrder = [
    'Homepage',
    'Shop',
    'About Us'
];

$sorted = $collection->sortBy(function($menuItem, $key) use ($correctOrder) {
    return array_search($menuItem->label, $correctOrder);
});

array_search() gives you the index of the value in an array.

Keep in mind the label of the collection and the value in the $correctOrder need to be of the same case for this to work. Not a very flexible approach, though, as the names might change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM