如何迭代包含 Laravel 中数组的 collections 数组?
How can I iterate over an array of collections containing arrays in Laravel?
我的 collection 使用以下查询实例化:$ClassesCollection = Classes::with('Queue')->whereIn('user_course_id', UserCourse::select('id')->where('user_id', $user->id))->get();
$ClassesCollection returns 想要的结果。但是,我只想要 Queue
结果。
所以我这样拆分
$classes = [];
foreach($ClassesCollection as $class){
array_push($classes, $class->Queue);
}
现在我有一个 collection 的数组,每个数组都包含 Queue
的数组。
如何遍历这些 collection 以在我的视图中分别显示每个 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
都包含几个属性,例如date
和class_id
。那么如何显示每个Queue的内容呢?
编辑:我认为会有更简洁的方法,但这就是我为遇到此问题的任何人解决问题的方法。
$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";
}
}
注释掉的代码也达到了预期的效果
使用pluck()
:
$queues = $ClassesCollection->pluck('Queue')->flatten();
我的 collection 使用以下查询实例化:$ClassesCollection = Classes::with('Queue')->whereIn('user_course_id', UserCourse::select('id')->where('user_id', $user->id))->get();
$ClassesCollection returns 想要的结果。但是,我只想要 Queue
结果。
所以我这样拆分
$classes = [];
foreach($ClassesCollection as $class){
array_push($classes, $class->Queue);
}
现在我有一个 collection 的数组,每个数组都包含 Queue
的数组。
如何遍历这些 collection 以在我的视图中分别显示每个 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
都包含几个属性,例如date
和class_id
。那么如何显示每个Queue的内容呢?
编辑:我认为会有更简洁的方法,但这就是我为遇到此问题的任何人解决问题的方法。
$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";
}
}
注释掉的代码也达到了预期的效果
使用pluck()
:
$queues = $ClassesCollection->pluck('Queue')->flatten();