从for循环中获取值

时间:2018-07-05 10:15:03

标签: php laravel laravel-5 laravel-5.3

我想在php中获取for循环值,我有一些名称,我想在每个名称后添加'/'并在循环外打印该值,我想从for循环中获取$ approver_name

foreach($co_practice as $co_practice_approver){
    // global $approver_name;
    if ($j >= 1) {
        $approver = users::where('id','=',$co_practice_approver)->first()->firstname;
        $approver_name = $approver_name . ' / ' . $approver;    
    } else {
        $approver_name = users::where('id','=',$co_practice_approver)->first()->firstname;
    }
}

 Hello {{$approver_name}}

现在我得到了没有approver_name的输出“ hello”如何打印在for循环中获取的approver_name

1 个答案:

答案 0 :(得分:2)

为什么不使用一次获取approver的{​​{1}}?循环获取数据将导致数据库中的多个查询。相反,您可以使用whereIn()

YourController.php

firstname

your_blade_file.blade.php

public function yourMethod {
    // your other logic here...

    // this will query to get all users matching ids in $co_practice array
    // and pluck() will get the array of user's firstname 
    $firstNames = UserModel::whereIn('id', $co_practice)->pluck('firstname');

    // this will concatenate firstnames separated by '/'
    $approver_name = implode(' / ', $firstNames->all());

    // this will pass the $approver_name variable to view
    return view('your_blade_file', compact('approver_name'));
}