Add merge method
patrickkusebauch opened this issue · comments
The real-world scenario:
I want to display day-wise data for the last month
I have an incomplete Collection
from en external data source - data for some days but not all. The collection is as follows:
key
is the datevalue
is the data
I want to fill in the blanks as to have an entry
for every date, but with blank/default values (so that I can display them in a graph)
Expected/naive solution:
$externalCollection; //However I get the data
$defaultCollection = Collection::from([/**something that gives me an entry with key for each day */]);
$dataWithFilledDefault = $defaultCollection->merge($externalCollection);
Ugly solution 1 - bypass collection
$externalCollection; //However I get the data
$defaultCollection = Collection::from([/**something that gives me an entry with key for each day */]);
$dataWithFilledDefault = Collection::from(array_merge($defaultCollection->toArray(), $externalCollection->toArray()));
Ugly solution 2 - search for each item in the other collection manually
$externalCollection; //However I get the data
$defaultCollection = Collection::from([/**something that gives me an entry with key for each day */]);
$dataWithFilledDefault = $defaultCollection->map(static function($value, $key) use ($externalCollection) {
return $externalCollection->has($key) ? $externalCollection->get($key) : $value;
});
You are probably looking for https://dusankasan.github.io/Knapsack/#Operations-replace or https://dusankasan.github.io/Knapsack/#Operations-replaceByKeys
Sorry, my bad. 'replace' was not really the keyword I had in mind for this operation so I missed it. You are absolutely right. It is exactly what I was looking for.