繁体   English   中英

循环浏览Laravel系列

[英]Loop over Laravel Collection

public function showJobCategoryContent($id){

     $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

     // Imagine here i got 5 data

     foreach ($jobsInfoById as $jobInfoById) {
          return  $current=$jobInfoById->created_at;
        //$trialExpires []= $current->addDays(30);
     }
}

如果我循环它只显示1数据。 如果使用array符号,它将显示1数据。

如果要获取所有created_at日期的数组,则不需要循环。

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return $jobsInfoById->pluck('created_at');
}

使用循环:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $dates = [];
    foreach ($jobsInfoById as $jobInfoById) {
        $dates[] = $current = $jobInfoById->created_at;
    }

    return $dates;
}

如果要在每个日期前增加30天:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}

看一下Laravel的收藏以及它们如何有用: 链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM