phparraysreplacereverse

Overwrite associative elements of one array with another associative array and reverse the array order


This is the First Array:

Array
(
    [6] => 1
    [8] => 1
    [9] => 5
)

Second Array:

Array
(
    [9] => 0
    [8] => 0
    [7] => 0
    [6] => 0
    [5] => 0
    [4] => 0
    [3] => 0
    [2] => 0
    [1] => 0
    [12] => 0
    [11] => 0
    [10] => 0
)

Desired Output Array:

Array
(
    [10] => 0
    [11] => 0
    [12] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
    [5] => 0
    [6] => 1
    [7] => 0
    [8] => 1
    [9] => 5
)

Simply I want to array to sort reverse but with the first array value. I have tried array_reverse but it only short the array in reverse and misplace the value of it.

Note: the desired array key is the previous 12 month

I have looked the suggested sort array technique but it didn't help


Solution

  • Check working demo here: https://eval.in/856000

    <?php 
    $array1 = array(6 => 1,
        8 => 1,
        9 => 5);
    
    $array2 = array(9 => 0,
        8 => 0,
        7 => 0,
        6 => 0,
        5 => 0,
        4 => 0,
        3 => 0,
        2 => 0,
        1 => 0,
        12 => 0,
        11 => 0,
        10 => 0);
    $mergedArray =[];
    
    foreach ($array2 as $key => $value) {
    
        if (array_key_exists($key, $array1)) {      
            if ($array1[$key] > $array2[$key]) {
              $mergedArray[$key] = $array1[$key];
            }
            else {
              $mergedArray[$key] = $array2[$key];
            }
        }
        else {
            $mergedArray[$key] = $array2[$key];
        }
    }
    
    print_r(array_reverse($mergedArray,true));
    
     ?>
    

    Output:

    Array
    (
        [10] => 0
        [11] => 0
        [12] => 0
        [1] => 0
        [2] => 0
        [3] => 0
        [4] => 0
        [5] => 0
        [6] => 1
        [7] => 0
        [8] => 1
        [9] => 5
    )