-1

我想在 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

4

1 回答 1

2

你为什么不立即获取approver'sfirstname呢?循环获取数据将导致数据库中的多个查询。相反,您可以使用whereIn()

你的控制器.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'));
}

your_blade_file.blade.php

//now you can print the $approver_name
Hello {{ $approver_name }}
于 2018-07-05T16:50:26.373 回答