Laravel Helper to merge Period arrays

334 Views Asked by At

Laravel Version:7.0

I would like to know how to create this helper.

Input is date range array. For example:

$input1 = [2020-07-19, 2020-07-25];
$input2 = [2020-07-26, 2020-08-01];
$input3 = [2020-08-01, 2020-08-07];
$input4 = [2020-10-01, 2020-10-07];
$input5 = [2020-10-19, 2020-10-25];

I would like to make one helper function.

function mergeDate($array)
{
   ...
}

So when I use this helper, I would like to get as following result.

$array = [$input1, $input2, $input3, $input4, $input5];
$mergedResult = mergeDate($array);

$mergedResult[0] = [2020-07-19, 2020-08-07];
$mergedResult[1] = [2020-10-01, 2020-10-07];
$mergedResult[2] = [2020-10-19, 2020-10-25];

Can anyone help me how to make mergeDate function?

Input period elements aren't overlapped.

Thank you!

1

There are 1 best solutions below

1
On

This would be my first guess at how to solve it.

    public function merge($array){
        $results = [];
        foreach ($array as $element){
            if (sizeof($results) == 0){
                array_push($results,$element);
            }else{
                $found = null;
                foreach ($results as $key => $r){
                    if (Carbon::parse($element[0])->equalTo(Carbon::parse($r[1]))) 
                    {
                        $found = $key;
                        break;
                    }
                }
                if (!is_null($found)){
                    $results[$found][1] = $element[1];
                }else{
                    array_push($results, $element);
                }
            }
        }
        return $results;
    }

It is a simple take on the problem. If our resulting array is empty we add the first element otherwise we iterate over the results to find a matching pair of the elements end date and the start date of the item in the results array. If we find a matching start end pair we replace the results end value with the elements end value. Otherwise we have no overlap and we can add it as a new item to the results array.

An interesting library to use would be the Spatie/Period library. https://github.com/spatie/period

@edit since the array is not sorted as mentioned in a comment above, you would have to sort it prior.