phparraysmultidimensional-arraygroupingfallbackvalue

Group rows of two 2d arrays by a shared column and add default values where no data is available


I have two two-dimensional arrays like

Array
(
[0] => Array
    (
        [0] => 2022-01-19
        [1] => 6
    )
[1] => Array
    (
        [0] => 2022-01-20
        [1] => 1
    )
[2] => Array
    (
        [0] => 2022-01-21
        [1] => 1
    )
[3] => Array
    (
        [0] => 2022-01-22
        [1] => 2
    )
)

and

Array
(
[0] => Array
    (
        [0] => 2022-01-17
        [1] => 6
    )
[1] => Array
    (
        [0] => 2022-01-18
        [1] => 1
    )
[2] => Array
    (
        [0] => 2022-01-21
        [1] => 1
    )
[3] => Array
    (
        [0] => 2022-01-23
        [1] => 2
    )
)

I need to merge them on related date values and I want the following result:

Array
(
[0] => Array
    (
        [0] => 2022-01-17
        [1] => 0
        [2] => 6
    )
[1] => Array
    (
        [0] => 2022-01-18
        [1] => 0
        [2] => 1
    )
[2] => Array
    (
        [0] => 2022-01-19
        [1] => 6
        [2] => 0
    )
[3] => Array
    (
        [0] => 2022-01-20
        [1] => 1
        [2] => 0
    )
[4] => Array
    (
        [0] => 2022-01-21
        [1] => 1
        [2] => 1
    )
[5] => Array
    (
        [0] => 2022-01-22
        [1] => 2
        [2] => 0
    )
[6] => Array
    (
        [0] => 2022-01-23
        [1] => 0
        [2] => 2
    )
)

I tried with the below code but not any success.

$final_array = [];
foreach ($openTicket as $val) {
    $closeTicketNo = 0;
    foreach ($closeTicket as $value) {
        if ($val[0] == $value[0]) {
            $closeTicketNo = $value[1];
        }
    }
    $final_array[] = [$val[0], $val[1], $closeTicketNo];
}

I get all the elements from the $openTicket but not get all the elements from a $closeTicket to my result array $final_array


Solution

  • This code first finds all of the unique dates (using array_unique) from the first values in each array (array_column fetches the values and array_merge puts them into 1 array).

    Then it indexes each array by the dates (using array_column again).

    Finally looping through the unique dates and adding a new element to the output with the values (using ?? 0 so that if no value is present the array is still filled properly)...

    $dates = array_unique(array_merge(array_column($openTicket, 0), array_column($closedTicket, 0)));
    $open = array_column($openTicket, 1, 0);
    $closed = array_column($closedTicket, 1, 0);
    $finalArray = [];
    foreach ($dates as $date) {
        $finalArray[] = [$date, $open[$date] ?? 0, $closed[$date] ?? 0];
    }