代码之家  ›  专栏  ›  技术社区  ›  calin24

按另一个数组对laravel集合排序

  •  0
  • calin24  · 技术社区  · 7 年前

    我在做这样的事情:

    // 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为的自定义数组对幻灯片集合进行排序?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andrii Lutskevych    7 年前

    从你的电脑上获取所有身份证 $slideOrderSetting

    $slideOrderArray = json_decode($slideOrderSetting, true);
    $slideOrderIDs = collect($slideOrderArray)->pluck('id')->toArray()
    

    About pluck() 方法

    $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)
    
    推荐文章