如何对给定的集合进行排序
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模型的一个实例
答案 0 :(得分:0)
修改
您可以使用combine()
来实现此目的。来自文档:
combine方法将集合的键与另一个数组或集合的值
组合在一起
因此,将索引作为$ correctOrder数组中的键,并将Collection映射到那些。
答案 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
中的值需要具有相同的大小写才能生效。但是,这并不是一种非常灵活的方法,因为名称可能会改变。