如何从集合中跳过前n个元素?

时间:2017-08-02 17:03:17

标签: php laravel collections

我想跳过一些来自集合的元素

$post_one = Post_one::all();
$post_two = Post_two::all();
$posts = collect();
if($post_one){
    foreach($post_one as $post){
        $posts->push($post);
    }
}
if($post_two){
    foreach($post_two as $post){
       $posts->push($post);
    }
}
//now i want to skip n=3, element form the collection of posts
$posts = $posts->sortBy('created_at')-<skip(3)->take(3);//does not work 

错误::方法跳过不存在。

2 个答案:

答案 0 :(得分:1)

要合并两个记录,您可以将merge方法与flatten,i,e

一起使用
$posts = $post_one->flatten(1)->merge($post_two)->sortBy('created_at');

然后使用filter来获得正确的结果:

$filtered = $posts->filter(function ($post, $key) {
    return $key > 2;
});

由于密钥从0 ... n。

开始,因此跳过前3个

或者您可以slice收藏:

$nextthree = $posts->slice(3, 3);

这会跳过3并从集合中获取接下来的3个。您可以访问原始馆藏$posts

此时保留集合的索引,但要将其重置为从0开始...... n只使用values()方法,即:

$nextthree = $posts->slice(3, 3)->values();

答案 1 :(得分:0)

您可以使用forPage()方法执行此操作。 像这样:

$posts = $posts->forPage($currentPage, $perPage);

Documentation

相关问题