按 laravel 中的旋转值排序
Orderby rotating values in laravel
我正在尝试使用 orderBy
方法在我的电子商务网站上为 "recommended" 创建按功能排序。这是一个简单的 orderby 示例:
if($params['sortby'] == 'numpricehl') $query->orderBy('price','desc');
我希望做的是通过旋转值来排序。示例:给定 10 种价格为:(10,20,30,....100) 的产品,它会这样排序(低、中、高、低、中、高)等,以便产品显示为这 (10,50,100,20,60,80)
执行此操作的最佳方法是什么?
这是一个适用于查询结果的解决方案:
$tiers = 3;
$result = [];
$products = Product::orderBy('price')->get();
$size = ceil($products->count() / $tiers);
$split = $products->pluck('price')->chunk($size);
while(!$split[0]->isEmpty()) {
for($tier = 0; $tier < $tiers; $tier++) {
if(!$split[$tier]->isEmpty()) {
$result[] = $split[$tier]->shift();
}
}
}
可能有 orderBy()
的数据库内解决方案,但我很确定它更复杂。
chunk()
部分还不理想,因为它将 10 个产品拆分为 4,4,2
。
您可以添加此以获得 4,3,3
:
if($products->count() % $tiers == 1) {
$split[2]->prepend($split[1]->pop());
}
我正在尝试使用 orderBy
方法在我的电子商务网站上为 "recommended" 创建按功能排序。这是一个简单的 orderby 示例:
if($params['sortby'] == 'numpricehl') $query->orderBy('price','desc');
我希望做的是通过旋转值来排序。示例:给定 10 种价格为:(10,20,30,....100) 的产品,它会这样排序(低、中、高、低、中、高)等,以便产品显示为这 (10,50,100,20,60,80)
执行此操作的最佳方法是什么?
这是一个适用于查询结果的解决方案:
$tiers = 3;
$result = [];
$products = Product::orderBy('price')->get();
$size = ceil($products->count() / $tiers);
$split = $products->pluck('price')->chunk($size);
while(!$split[0]->isEmpty()) {
for($tier = 0; $tier < $tiers; $tier++) {
if(!$split[$tier]->isEmpty()) {
$result[] = $split[$tier]->shift();
}
}
}
可能有 orderBy()
的数据库内解决方案,但我很确定它更复杂。
chunk()
部分还不理想,因为它将 10 个产品拆分为 4,4,2
。
您可以添加此以获得 4,3,3
:
if($products->count() % $tiers == 1) {
$split[2]->prepend($split[1]->pop());
}