在laravel 5.7中,我尝试使用collection重新制作一小部分应用程序
$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList = [];
$siteSubscriptions = SiteSubscription
::getByActive(true)
->orderBy('id', 'asc')
->get();
foreach ($siteSubscriptions as $next_key => $nextSiteSubscription) {
$is_found = false;
foreach ($selectedSubscriptions as $next_value) {
if ($nextSiteSubscription->id == (int)$next_value) {
$is_found = true;
break;
}
}
$siteSubscriptionsList[] = (object)['name' => $nextSiteSubscription->name, 'id' => $nextSiteSubscription->id, 'checked' => $is_found];
}
喜欢:
$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList = SiteSubscription
::getByActive(true)
->orderBy('id', 'asc')
->get()
->map(function ( $item, $selectedSubscriptions ) {
$is_found = false;
foreach ($selectedSubscriptions as $next_value) {
if ($item->id == (int)$next_value) {
$is_found = true;
break;
}
}
return (object)['name' => $item->name, 'id' => $item->id, 'checked' => $is_found];
})
->all();
但是我需要在地图函数中设置附加参数$ selectedSubscriptions,因为它不起作用,因为我在地图中看到 该功能的值为“ 0”。 正确程度如何?
答案 0 :(得分:4)
在将数据传递到->map()
闭包时,使用use
语句(在function()
调用之后):
$selectedSubscriptions = [1,2,3];
$siteSubscriptionsList = SiteSubscription
::getByActive(true)
->orderBy('id', 'asc')
->get()
->map(function ($item, $key) use ($selectedSubscriptions) {
$is_found = false;
foreach ($selectedSubscriptions as $next_value) {
if ($item->id == (int)$next_value) {
$is_found = true;
break;
}
}
return (object)['name' => $item->name, 'id' => $item->id, 'checked' => $is_found];
})
->all();
->map()
的第二个参数将始终是$key
的变量。
侧面注记:您可以使用以下方法减少foreach
的ID检查:
$is_found = collect($selectedSubscriptions)->contains($item->id);