【发布时间】:2023-12-20 06:04:02
【问题描述】:
我编写了一个简单的代码来打印出关联数组的元素,但它处于条件循环中,尽管我认为 foreach 编写正确。它不起作用。 foreach 循环使用了一个由路由传递的变量。
return view('results')
->with('name', $name)
->with('state', $state)
->with('pms', $pms)
->with('hasresult', $hasresult)
->with('err', $err)
->with('errNoEntries', $errNoEntries);
代码如下:
@extends('layouts.master')
@section('title')
Search Results
@endsection
@section('content')
<h2>Australian Prime Ministers</h2>
@if ($errNoEntries) {{-- meaning the data was entered incorrectly --}}
<p class='alert'>{{$err}}</p>
@elseif (!$hasresult)
<p class='alert'>No Results found</p>
@else
<table class="bordered">
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>From</th>
</tr>
</thead>
<tbody>
@foreach($pms as $pm)
<tr>
<td>{{$pm['index']}}</td>
<td>{{$pm['name']}}</td>
<td>{{$pm['from']}}</td>
</tr>
@endforeach
</tbody>
</table>
@endif
<form method="post" action="searchresult">
{{csrf_field()}}
<table>
<tr><td>Name: </td><td><input type="text" name="name"></td></tr>
<tr><td>Year: </td><td><input type="text" name="year"></td></tr>
<tr><td>State: </td><td><input type="text" name="state"></td></tr>
<tr><td colspan=2><input type="submit" value="Search">
<input type="reset" value="Reset"></td></tr>
<table>
</form>
@endsection
【问题讨论】:
-
给出了哪个错误? $err 的输出是什么?
-
ErrorException 为 foreach() 提供的参数无效(查看:/home/ubuntu/workspace/WebAppDev/Week4/assoc-laravel/resources/views/results.blade.php)
-
err 是一个字符串类型的变量。顶部 if elseif 工作正常并且错误检查工作正常,它只是 else 位,特别是关联数组的打印。 $pms 中的一个典型元素 array = $pms = array( array('index' => '1', 'name' => 'Edmund Barton', 'from' => '1 January 1901', 'to' => '24 September 1903', 'party' => 'Protectionist', 'duration' => '2 年 8 个月 24 天', 'state' => 'New South Wales'));
标签: laravel loops associative-array blade