Php 从for循环中获取值
我想在php中获取for循环值我有一些名称,我想在每个名称后添加“/”,并在循环外打印值,我想从for循环中获取$approver\u名称Php 从for循环中获取值,php,laravel,laravel-5,laravel-5.3,Php,Laravel,Laravel 5,Laravel 5.3,我想在php中获取for循环值我有一些名称,我想在每个名称后添加“/”,并在循环外打印值,我想从for循环中获取$approver\u名称 foreach($co_practice as $co_practice_approver){ // global $approver_name; if ($j >= 1) { $approver = users::where('id','=',$co_practice_approver)->first()->
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}}
现在,我得到了输出“hello”而没有approver\u name如何打印我为循环获取的approver\u name为什么不立即获取
approver
的firstname
?在循环中获取数据将导致数据库中出现多个查询。相反,你可以使用
YourController.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'));
}
//now you can print the $approver_name
Hello {{ $approver_name }}
您的_blade_文件.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'));
}
//now you can print the $approver_name
Hello {{ $approver_name }}
问题是?你记得吗?这是一个.blade文件吗?我想你的语法是错误的尝试从
{{$approver\u name}}
中删除{{{{}}
你能显示完整的视图吗?是的,这是一个刀片文件。当我在forloop外部获取approver值时,会打印approver\u名称。请看$approver\u名称已经被覆盖,如果结果返回null,你只会看到Hello