2017-08-02 97 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();