按另一个数组对 laravel 集合进行排序
sort a laravel collection by another array
我想按 ID 对集合进行排序,其中 ID 存储在自定义数组中。
我正在做这样的事情:
// get the slides images
$allSlides = DB::table('homepage_slides')->paginate(10);
// slideOrderSetting is a json, storing the order for slides [{"id":4},{"id":1},{"id":2},{"id":3},{"id":5},{"id":6}]
$slideOrder = json_decode($slideOrderSetting, true);
// sort the slides
$slides = array();
foreach ($slideOrder as $order){
foreach ($allSlides as $slide){
if((int)$order['id'] === (int)$slide->SlideID){
array_push($slides, $slide);
break;
}
}
}
// get the slide array sorted
return $slides;
数组幻灯片已排序,但是....问题是我丢失了 $allSlides 集合中的分页和其他内容。
如何使用带有 id 的自定义数组对幻灯片集合进行排序?
从您的 $slideOrderSetting
:
获取所有 ID
$slideOrderArray = json_decode($slideOrderSetting, true);
$slideOrderIDs = collect($slideOrderArray)->pluck('id')->toArray()
Aboutpluck()
方法
然后获取幻灯片:
$slides = DB::table('homepage_slides')
->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
->paginate(10)
或
$slides = DB::table('homepage_slides')
->whereIn('id', $slideOrderIDs)
->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
->paginate(10)
我想按 ID 对集合进行排序,其中 ID 存储在自定义数组中。
我正在做这样的事情:
// get the slides images
$allSlides = DB::table('homepage_slides')->paginate(10);
// slideOrderSetting is a json, storing the order for slides [{"id":4},{"id":1},{"id":2},{"id":3},{"id":5},{"id":6}]
$slideOrder = json_decode($slideOrderSetting, true);
// sort the slides
$slides = array();
foreach ($slideOrder as $order){
foreach ($allSlides as $slide){
if((int)$order['id'] === (int)$slide->SlideID){
array_push($slides, $slide);
break;
}
}
}
// get the slide array sorted
return $slides;
数组幻灯片已排序,但是....问题是我丢失了 $allSlides 集合中的分页和其他内容。
如何使用带有 id 的自定义数组对幻灯片集合进行排序?
从您的 $slideOrderSetting
:
$slideOrderArray = json_decode($slideOrderSetting, true);
$slideOrderIDs = collect($slideOrderArray)->pluck('id')->toArray()
Aboutpluck()
方法
然后获取幻灯片:
$slides = DB::table('homepage_slides')
->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
->paginate(10)
或
$slides = DB::table('homepage_slides')
->whereIn('id', $slideOrderIDs)
->orderByRaw(DB::raw('FIELD(id, '.implode(', ', $slideOrderIDs).')'))
->paginate(10)