如何按数组排序?

时间:2017-06-17 20:15:25

标签: php laravel sorting collections

如何对给定的集合进行排序

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

借助这个数组

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

所以最后我会得到

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

MenuPosition是Eloquent模型的一个实例

2 个答案:

答案 0 :(得分:0)

修改

您可以使用combine()来实现此目的。来自文档:

  

combine方法将集合的键与另一个数组或集合的值

组合在一起

因此,将索引作为$ correctOrder数组中的键,并将Collection映射到那些。

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

答案 1 :(得分:0)

假设$collection包含菜单项,请尝试以下方法:

$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()为您提供数组中值的索引。

请记住集合的label,并且$correctOrder中的值需要具有相同的大小写才能生效。但是,这并不是一种非常灵活的方法,因为名称可能会改变。