DusanKasan / Knapsack

Collection pipeline library for PHP

Home Page:http://dusankasan.github.io/Knapsack/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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 date
  • value 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;
        });

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.