Home > database >  add 1st array value to 2nd array based on key match
add 1st array value to 2nd array based on key match

Time:08-31

I am trying to add 1st array value to 2nd array based on key match but not success with array_merge function see example of what i doing below

Array1
(
    [99] => 99
    [98] => 98
    
)
Array2


(
    [99] => Array
        (
            [0] => 1300
            [1] => 1500
            [2] => 1618
            [3] => 2704
            [4] => 1401
            [5] => 1900
            [6] => 1100
            [7] => 4232
            [8] => 4233
        )

    [98] => Array
        (
            [0] => 1400
            [1] => 4802
            [2] => 1601
            [3] => 1603
            [4] => 1100
            [5] => 1900
        )
    )

my code so far returning me wrong output like this

$finalArray = array_merge($Array1, $Array2);

what i am expecting

finalArray
(
    
   [99] => Array
        (
            [0] => 1300
            [1] => 1500
            [2] => 1618
            [3] => 2704
            [4] => 1401
            [5] => 1900
            [6] => 1100
            [7] => 4232
            [8] => 4233
            [9] => 99
        )

    [98] => Array
        (
            [0] => 1400
            [1] => 4802
            [2] => 1601
            [3] => 1603
            [4] => 1100
            [5] => 1900
            [6] => 98
        )
    )

i have tried array_merge, array_push & array combine as well but not success please somebody help me on this

CodePudding user response:

This should do the work for you

Example code

   <?php
    $arr1 = Array
    (
        '99' => 99,
        '98' => 98
        
    );

    $arr2 = Array(
        '99' => Array
            (
                '0' => 1300,
                '1' => 1500,
                '2' => 1618,
                '3' => 2704,
                '4' => 1401,
                '5' => 1900,
                '6' => 1100,
                '7' => 4232,
                '8' => 4233
            ),
        '98' => Array
            (
                '0' => 1400,
                '1' => 4802,
                '2' => 1601,
                '3' => 1603,
                '4' => 1100,
                '5' => 1900
            )
        );
        
     foreach($arr1 as $key => $value){
      if(isset($arr2[$key])){
        array_push($arr2[$key],$value);
      }else{
        $arr2[$key] = $value;
      }
    }
        
        print_r($arr2);
  • Related