2017-08-02 98 views
1

我想从收集如何从集合中跳过第n个元素?

$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 

错误::方法跳过不存在跳过一些元素。

+0

你想跳过3后取3以及? –

+0

你有没有找到其他方法来做到这一点? –

回答

1

要合并两个记录,您可以使用mergeflatten,I,E

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

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

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

这将跳过第3,因为键从0 ... n开始。

或者你可以slice集合:

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

此跳过3,并采取从集合未来3。您可以访问原始收藏品$posts

此时采集的指标被保留,但将其复位,从0开始... N只使用values()方法,即:

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