2017-08-01 42 views
0

我写了一个简单的代码来打印出关联数组的元素,但它是在一个条件循环中,虽然我认为foreach被正确写入。它不起作用。 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 
+0

给出了哪个错误?和$ err的输出是什么? –

+0

ErrorException 为foreach()提供的无效参数(视图:/home/ubuntu/workspace/WebAppDev/Week4/assoc-laravel/resources/views/results.blade.php) –

+0

err是一个字符串类型变量。顶部如果elseif工作正常并且错误检查工作正常,则它只是其他位,特别是关联数组的打印。 ('index'=>'1','name'=>'Edmund Barton','from'=>'1901年1月1日','to'='pms array = $ pms = array( array) > 1903年9月24日''party'=>'Protectionist','duration'=>'2年,8个月,24天','州'=>'新南威尔士')); –

回答

1

我想你应该试试这个:

@if(is_object($pms) || is_array($pms)) 
@foreach($pms as $pm) 
       <tr><td>{{$pm['index']}}</td><td>{{$pm['name']}}</td><td>{{$pm['from']}}</td></tr> 
      @endforeach 

@endif 

注意:可能是你的$ PMS是不是数组或对象

+0

谢谢。虽然我没有只是方法,我调试,发现我的数组确实是由于逻辑错误而变空。该代码是正确的 –