0
Array1
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 0  
        )

    [1] => Array
        (
            [date] => 2022-12-02
            [result] => 0
        )


    [2] => Array
        (
            [date] => 2022-12-03
            [result] => 0
        )
                .
                .
                .
                .

    [31] => Array
        (
            [date] => 2022-12-31
            [result] => 0
        )

)



Array2
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 45
        )

    [1] => Array
        (
            [date] => 2022-12-03
            [result] => 15
        )
                .
                .
                .
                .

    [25] => Array
        (
            [date] => 2022-12-31
            [result] => 25
        )

)

Array3
(
    [0] => Array
        (
            [date] => 2022-12-01
            [result] => 45
        )

    [1] => Array
        (
            [date] => 2022-12-02
            [result] => 0
        )


    [2] => Array
        (
            [date] => 2022-12-03
            [result] => 15
        )
                .
                .
                .
                .

    [31] => Array
        (
            [date] => 2022-12-31
            [result] => 25
        )

)

I want to combine Array1 and Array2 into Array3. Array one contain all days of the months with empty value and Array2 only contain the days with values. So, I want to loop through both of the array if the date in Array2 then use the value of Array2 else use the 0 value of Array1. I try using for each loop but the result in Array! didn't make any changes Below is my code:

foreach($Array1 as $arr1){
       foreach($Array2 as $arr2){
                if($arr1['date'] == $arr2['date']){
                    $arr1['date'] = $arr2['date'];
                    $arr1['result'] = $arr2['result'];
                }
       }
}
Francis.C
  • 5
  • 3

1 Answers1

1

You need to make $arr1 a reference variable so that assigning to it modifies the array. Otherwise you're modifying a copy of the array and the changes are lost when the loop ends.

foreach($Array1 as &$arr1){

There's also no need for $arr1['date'] = $arr2['date']; since the if condition means they're the same.

Barmar
  • 741,623
  • 53
  • 500
  • 612