遍历 Laravel 控制器中的结果集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28256103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating through result set in Laravel controller
提问by AnchovyLegend
I am trying to simply iterate though a result set in laravel on the controller side. This is what I tried but I get the following error:
我试图简单地迭代控制器端 laravel 中的结果集。这是我尝试过的,但出现以下错误:
Cannot use object of type stdClass as array
Controller snippet:
控制器片段:
$result = DB::select($query);
foreach($result as $r){
echo $r['email'];
}
I appreciate any help with this,
我感谢任何帮助,
Thanks in advance!
提前致谢!
回答by Giedrius
You need to use it as an object:
您需要将其用作对象:
$result = DB::select($query);
foreach($result as $r){
echo $r->email;
}
Or if for some reason you want to use it as array, you need to convert it first:
或者,如果出于某种原因要将其用作数组,则需要先将其转换:
$result = DB::select($query)->toArray();
foreach($result as $r){
echo $r['email'];
}
回答by Lord
After pulling data from database you can convert it to array but it is optional, it's depends on your necessity then you can simply use the foreachto loop through to each distinct object and get access their property
从数据库中提取数据后,您可以将其转换为数组,但它是可选的,这取决于您的需要,然后您可以简单地使用foreach循环到每个不同的对象并访问它们的属性
$data = DB:: table('categories')
->where('parent_id', $request->value)
->get()->toArray();
$output = '<option value="">Select '.ucfirst($request->dependent).'</option>';
foreach($data as $row){
$output.= '<option value="'.$row->id.'">'.$row->title.'</option>';
}
return response($output, 200);