首页 > 解决方案 > Laravel:看不到'radio'以外的变量值

问题描述

我正在尝试使用 foreach 语句遍历数组。我从 API 获取数组,而不是我的。我在刀片中使用来自 Laravel 的 foreach。如果我通过阵列以某种方式在我的刀片中,每个都有一个类型,它只能看到“无线电”类型。没有复选框或文本区域。想知道为什么以及我能做些什么来解决它。

<form action="/sendForm" method="post">@csrf
            @foreach($survey['data']['formCategories'] as $category)
                <h3 id="{{$category['name']}}">{{$category['name']}}</h3>  <!-- Enquete -->
                <hr/>

                @foreach($category['formQuestions'] as $question)

                @if($question['type'] === 'header' || $question['type'] === 'text' || $question['type'] === 'date')
                    <!-- Don't show -->
                    @else

                        <div>
                            <p class="questions">{{$question['name']}}</p>

                            <fieldset id="{{$question['id']}}" class="form-group">
                                @foreach($question['formOptions'] as $answer)
                                    @if($question['type'] === "textarea" || $question['type'] === "paragraph")
                                        TextArea
                                    @elseif($question['type'] === "checkbox")
                                        Checkbox
                                    @elseif($question['type'] === "radio")
                                        Radio
                                    @endif
                                @endforeach
                            </fieldset>
                        </div>
                    @endif
                @endforeach
            @endforeach
            <input type="submit" value="Sent" class="submit-btn" id="versturen">
</form>

最后我想根据类型显示一个表单输入。因此,如果类型是 textarea,则显示 textarea,如果是 checkbox,则显示一个复选框,与 radio 相同。

我很抱歉语法不好,我知道这不是最好的问题,但我不知道还能问什么。

编辑

API 响应

name: '',
formCategories: [ //Different Categories
    0:  name:''
    formQuestions: [ //Questions
    0:  name: '',
        type: '',   //Is either Radio, Checkbox or TextArea
        formOptions: [ //Possible answers if necessary, empty if not needed.
        0:  name: ''
        ]
    ],
],

编辑 2

dd 类型为 textarea:

array:7 [
name: '',
formQuestions: [
    name: '',
    type: 'textarea',
    ]
]

标签: phplaravelif-statementforeachlaravel-blade

解决方案


你在循环中调用了错误的对象,你应该调用 $answer,所以改变

@foreach($question['formOptions'] as $answer)
@if($question['type'] === "textarea" || $question['type'] === "paragraph")
     TextArea
@elseif($question['type'] === "checkbox")
     Checkbox
@elseif($question['type'] === "radio")
     Radio
@endif
@endforeach

@foreach($question['formOptions'] as $answer)
@if($answer['type'] === "textarea" || $answer['type'] === "paragraph"
     TextArea
@elseif($answer['type'] === "checkbox")
     Checkbox
@elseif($answer['type'] === "radio")
     Radio
@endif
@endforeach

因为你这样做的方式,你只是调用循环的第一个实例,在 $question,作为它的一个数组。但是 $answer 是 foreach 循环数组中的特定对象。


推荐阅读