【问题标题】:how to skip first n element from collection?如何从集合中跳过第一个 n 元素?
【发布时间】:2017-08-02 17:03:16
【问题描述】:

我想跳过,集合中的一些元素

$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 

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

【问题讨论】:

  • 跳过 3 后也要拿 3 吗?
  • 你找到其他方法了吗?

标签: php laravel collections


【解决方案1】:

要合并两条记录,您可以使用merge 方法和flatten,即,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();

【讨论】:

    【解决方案2】:

    您可以使用forPage() 方法来做到这一点。 像这样:

    $posts = $posts-&gt;forPage($currentPage, $perPage);

    Documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 2023-01-26
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多