Laravel:迭代对象数组

时间:2017-03-09 16:50:56

标签: arrays laravel object iteration blade

好的,所以我在控制器中创建了一系列对象

$displayRooms[$room] = $this->getNextEvent($events, $room);

return view('schedule')->with(['displayRooms' => $displayRooms]);

然后在我看来,我能够遍历数组并获得$ room和$ events

@foreach ($displayRooms as $room => $events)
    {{ var_dump($events) }}
@endforeach

var_dump($ events)产生

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:
object(stdClass)[176]
  public 'available' => boolean false
  public 'room' => string 'Room 318' (length=8)
  public 'summary' => string 'Chem 3090 Himmeldirk' (length=20)
  public 'startTime' => string '12:00pm' (length=7)
  public 'endTime' => string '3:00pm' (length=6)
  public 'startDay' => string '03/21/17' (length=8)
  public 'endDay' => string '03/21/17' (length=8)

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:null

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:null

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:
object(stdClass)[226]
  public 'available' => boolean false
  public 'room' => string 'Room 513 (Voinovich Room)' (length=25)
  public 'summary' => string 'Reynolds' (length=8)
  public 'startTime' => string '1:00pm' (length=6)
  public 'endTime' => string '3:00pm' (length=6)
  public 'startDay' => string '03/21/17' (length=8)
  public 'endDay' => string '03/21/17' (length=8)

我的问题是如何迭代Blade中的事件对象以访问对象的属性,以便我可以将它们传递给局部视图?

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的要求(以及你的数据结构),那么这应该有效。您可以迭代事件对象数组以单独访问每个事件对象,然后迭代每个事件对象以访问每个单独的属性/值。此代码应嵌套在您的第一个foreach中(用它替换转储)。

@foreach($events as $event) 
    @foreach ($event as $prop => $value) 
        // do whatever with prop / values
    @endforeach
@endforeach

如果您不需要一次访问一个对象的每个属性/值,那么我会建议这样做。

@foreach($events as $event)
    // do whatever with each event
    {{ var_dump($event->available) }}
@endforeach