【问题标题】:PHP Laravel alternate push based on conditionPHP Laravel 基于条件的交替推送
【发布时间】:2021-09-06 18:46:12
【问题描述】:

我在表格中有字段 观看次数最多top_rated

    $most_viewed_posts = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->get();
    $top_rated_posts = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->get();
    $featured_collection = collect();
    foreach ($most_viewed_posts as $most_viewed_post)
        $featured_collection->push($most_viewed_post);
    foreach ($top_rated_posts as $top_rated_post)
        $featured_collection->push($top_rated_post);
    $featured_posts = $featured_collection->sortBy('id', SORT_NUMERIC)->reverse()->chunk(2);

我在这里想要完成的是将结果分成 2 个。因为我在下面的图片中显示它。这是一个旋转木马。块中的第一个结果应该是 most_viewed,第二个是 top_rated。

现在的问题是有时,most_viewed 帖子在评分最高的列中。有没有可能chunk中的item总是most_view和top_rated?

【问题讨论】:

    标签: php laravel laravel-blade


    【解决方案1】:

    你为什么要以如此复杂的方式完成它? 为什么不简单:

    $most_viewed_post = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->first();
    $top_rated_post = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->first();
    $featured_posts = collect([$most_viewed_post, $top_rated_post]);
    

    更新。

    要获得观看次数最多 + 评分最高的配对集合,您可以使用 zip() 方法 (https://laravel.com/docs/8.x/collections#method-zip):

    $most_viewed_posts = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->get();
    $top_rated_posts = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->get();
    
    $featured_collection = $most_viewed_posts->zip($top_rated_posts);
    
    //later you can iterate them this way:
    foreach($featured_collection as [$most_viewed, $top_rated]) {
        //...output
    }
    

    【讨论】:

    • 我不仅显示 1 most_viewed。我显示所有 most_viewed 项目等与 top_rated。就像我说的旋转木马。每个轮播应有 1 个观看次数最多和 1 个评分最高
    • @RandyCorpuz 查看我的更新答案。通过这种方式,您可以创建一组对 [[most viewed1, top rated1], [most viewed2, top rated2], ...]。您只需要处理两个集合具有不同帖子数的情况。
    • 完美..谢谢。不知道 zip 集合存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2013-12-11
    相关资源
    最近更新 更多