php - Laravel 请求 - 检索数据
问题描述
我需要一些帮助来遍历我通过表单提交的数据:
{
"_token": "MYJZs0EIuYMKvD7Y56R8DluxGu9vKJuNkMxXy2Ll",
"name": "Routine 1",
"sections": {
"section-1": {
"section-name": "Section 1",
"exercises": {
"1": {
"name": "Exercise 1"
},
"2": {
"name": "Exercise 2"
}
}
},
"section-2": {
"section-name": "Section 2",
"exercises": {
"3": {
"name": "Exercise 21"
},
"4": {
"name": "Exercise 22"
}
}
}
},
"submit": "Submit"
}
我如何正确循环并访问单个值?我希望它打印出来:
<h2>Section 1</h2><br/>
<p>Exercise 1</p><br/>
<p>Exercise 2</p><br/>
<h2>Section 2</h2><br/>
<p>Exercise 21</p><br/>
<p>Exercise 22</p><br/>
我被困在这里:
public function store(Request $request)
{
$data = $request;
$html = "";
foreach($data as $element){
$html .= "<h2>" . $element->name .'</h2>';
}
return $html;
}
我知道它的 store 方法,但在我保存它的数据之前,我想返回自己纯 html 以查看是否一切正常,所以忽略它。
解决方案
我知道它的 store 方法,但在我保存它的数据之前,我想返回自己纯 html 以查看是否一切正常,所以忽略它。
如果你想这样做..为什么要打服务器?您可以向用户显示带有请求数据的模式,然后在确认后继续向服务器发送请求..
PS:我假设您正在使用 Blade。
无论如何,忽略这一点,您可以将数据返回到同一个视图并在那里循环数据:
public function confirmData(Request $request)
{
$data = $request->all(); // Getting your values (I'll suggest you to use only() instead)
return view('some_view')->with('data', $data);
}
那么在你看来:
@foreach($data as $key => $value)
<span>{{ $value }}</span>
@endforeach
更新
为了实现你想要的尝试这个(我基于你发布的json):
public function confirmData(Request $request)
{
$sections = $request->get('sections');
$html = '';
foreach($sections as $section)
{
$html .= "<h2> { $section['section-name'] } </h2>";
foreach($section['exercises'] as $exercise)
{
$html .= "<p> { $exercise['name'] } </p>";
}
}
// ...
return $html;
}
推荐阅读
- javascript - 如何在reactjs中单击删除表格行?
- swift - SpriteKit 中的触摸持续时间
- c# - 从继承类中获取属性信息,在静态函数内部
- php - 按标准将数据从内存表传输到生产
- search - 在 MailKit 中搜索电子邮件不是使用 SearchQuery 方法,而是使用简单的文本字符串条件
- android - Android Studio 应用程序构建但不安装或运行某些风格
- python - GStreamer 动态更改图像大小
- flutter - Flutter:如何逐步填充可滚动小部件直到其可滚动
- ios - 如何从objective-c中的函数调用字符串中获取方法选择器?
- elasticsearch - 通过 API 将用户添加到 AWS elasticsearch kibana 仪表板