如何在包含Laravel中的数组的集合数组上进行迭代?

时间:2018-09-10 13:54:46

标签: arrays eloquent laravel-5.6 eager-loading laravel-5.7

我的收藏集使用以下查询实例化:$ClassesCollection = Classes::with('Queue')->whereIn('user_course_id', UserCourse::select('id')->where('user_id', $user->id))->get();

$ ClassesCollection返回所需的结果。但是,我只想要Queue结果。

所以我以这种方式拆分

$classes = [];

    foreach($ClassesCollection as $class){
        array_push($classes, $class->Queue);
    }

现在我有一个集合数组,每个集合都包含Queue s个数组。

如何在我的视图中遍历这些集合以分别显示Queue的每个数组的内容?

这就是$classes所拥有的

array:10 [▼
  0 => Collection {#968 ▼
    #items: array:12 [▼
      0 => Queue {#841 ▶}
      1 => Queue {#842 ▶}
      2 => Queue {#843 ▶}
      3 => Queue {#844 ▶}
      4 => Queue {#845 ▶}
      5 => Queue {#846 ▶}
      6 => Queue {#847 ▶}
      7 => Queue {#848 ▶}
      8 => Queue {#849 ▶}
      9 => Queue {#850 ▶}
      10 => Queue {#851 ▶}
      11 => Queue {#852 ▶}
    ]
  }
  1 => Collection {#969 ▶}
  2 => Collection {#970 ▶}
  3 => Collection {#971 ▶}
  4 => Collection {#972 ▶}
  5 => Collection {#973 ▶}
  6 => Collection {#974 ▶}
  7 => Collection {#975 ▶}
  8 => Collection {#976 ▶}
  9 => Collection {#977 ▶}
]

每个Queue拥有几个属性,例如dateclass_id。那我该怎么做才能显示每个队列的内容?

编辑:我以为会有一种更清洁的方法,但这是我为遇到此问题的任何人解决我的问题的方法。

$count = 0;
foreach($classes as $collection => $queue){
       /*$count = count($queue) - 1;
       for($i = 0; $i <= $count; $i++){
        echo $queue[$i]->date."\n";
       }*/
       foreach($queue as $Q){
        echo $Q->date."\n";
       }
}

注释掉的代码也能达到预期的效果。

1 个答案:

答案 0 :(得分:0)

使用pluck()

$queues = $ClassesCollection->pluck('Queue')->flatten();