PHP Laravel 根据条件交替推送
PHP Laravel alternate push based on condition
我在 table 中有字段
most_viewed 和
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 post 在最高评价列中。是否有可能块中的项目总是 most_view 和 top_rated?
你为什么要用这么复杂的方式完成它?
为什么不简单:
$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
}
我在 table 中有字段 most_viewed 和 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 post 在最高评价列中。是否有可能块中的项目总是 most_view 和 top_rated?
你为什么要用这么复杂的方式完成它? 为什么不简单:
$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
}