'How to merge two associative arrays

I have two associative 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 with the date and want a result array-like below

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 1:[1]

You can try like this

$array1 = [
    ['2022-01-19',6],
    ['2022-01-20',1],
    ['2022-01-21',0]
];

$array2 = [
    ['2022-01-17',6],
    ['2022-01-20',2],
    ['2022-01-21',1]
];


function mergeMultiple($array1,$array2){
    foreach($array1 as $item1){
        $mergedArray[$item1[0]] = $item1;
    }

    foreach($array2 as $item2){
        if(isset($mergedArray[$item2[0]])){
             array_push($mergedArray[$item2[0]],$item2[1]);
             $mergedArray[$item2[0]] = $mergedArray[$item2[0]];
        }else{
          $mergedArray[$item2[0]] = $item2;
        }
    }

    return array_values($mergedArray);
}

$mergedArray = mergeMultiple($array1,$array2);
ksort($mergedArray);
print_r($mergedArray);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1