首页 > 解决方案 > 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 以查看是否一切正常,所以忽略它。

标签: phplaravel

解决方案


我知道它的 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;
}

推荐阅读