DusanKasan / Knapsack

Collection pipeline library for PHP
http://dusankasan.github.io/Knapsack/
MIT License
535 stars 56 forks source link

Add merge method #58

Closed patrickkusebauch closed 4 years ago

patrickkusebauch commented 4 years ago

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:

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;
        });
DusanKasan commented 4 years ago

You are probably looking for https://dusankasan.github.io/Knapsack/#Operations-replace or https://dusankasan.github.io/Knapsack/#Operations-replaceByKeys

patrickkusebauch commented 4 years ago

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.