Laravel 合并多次分组的集合
我有一个集合分组(多次)如下:Laravel 合并多次分组的集合,laravel,collections,laravel-7,laravel-collection,Laravel,Collections,Laravel 7,Laravel Collection,我有一个集合分组(多次)如下: Illuminate\Support\Collection {#1883 ▼ #items: array:1 [▼ 57082 => Illuminate\Support\Collection {#1885 ▼ #items: array:1 [▼ "07-2021" => Illuminate\Database\Eloquent\Collection {#1863 ▼ #
Illuminate\Support\Collection {#1883 ▼
#items: array:1 [▼
57082 => Illuminate\Support\Collection {#1885 ▼
#items: array:1 [▼
"07-2021" => Illuminate\Database\Eloquent\Collection {#1863 ▼
#items: array:1 [▼
343 => Illuminate\Database\Eloquent\Collection {#1864 ▼
#items: array:1 [▶]
}
]
}
]
}
]
}
我有另一个集合,它可能有相同的值,也可能没有,我需要用合并的元素合并这两个集合
我尝试过这个,但没有成功(我失去了第一个“组”):
我希望您使用
mapWithKeys()
错误的方法松开键,通常使用该方法,返回一个关联数组,表示要映射到的键和值
因此,将闭包逻辑更改为以下,将保留第一个组
$collection = $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
return [$key => $collection];
或者,只需使用map()
即可解决您的问题,map()
将保留密钥
$fstCollection = $fstCollection->map(function ($items, $key) use ($sndCollection) {
return $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
});
$fstCollection = $fstCollection->map(function ($items, $key) use ($sndCollection) {
return $sndCollection->get($key) ? $items->merge($sndCollection->get($key)) : $items;
});