phparraysmultidimensional-arraymappingmerging-data

Use row values from a 2d array as row keys in another 2d array


I have 2 Multidimensional arrays as follow:

Array1:

Array ( 
        [0] => Array ( 
                       [0] => 2D Design 
                       [1] => 3D Design & Modeling) 
        [1] => Array ( [0] => Android Developer 
                       [1] => Artificial Intelligence 
                       [2] => Web Developer)
       )

Array2:

Array ( 
        [0] => Array ( 
                       [0] => 5 
                       [1] => 10) 
        [1] => Array ( [0] => 2 
                       [1] => 4 
                       [2] => 6)
       )

I want to combine the above 2 arrays as key and value as below.

Array ( 
        [0] => Array ( 
                       [2D Design] => 5 
                       [3D Design & Modeling] => 10 ) 
        [1] => Array ( 
                       [Android Developer] => 2 
                       [Artificial Intelligence] => 4 
                       [Web Developer] => 6 )
      )   

Solution

  • use array_combine() function creates an array by using the elements from one "keys" array and one "values" array.

    Note: Both arrays must have equal number of elements!

    First parameter array taken as key of new array and second parameter taken as value new array .

    $new_array=array();
    
    for($i=0;$i<count($arr1);$i++)
    {
    
       $new_array[$i]=array_combine($arr1[$i],$arr2[$i]); 
    }
    
    print_r($new_array);
    

    Output :

     Array
    (
     [0] => Array
        (
            [2D Design] => 5
            [3D Design & Modeling] => 10
        )
    
    [1] => Array
        (
            [Android Developer] => 2
            [Artificial Intelligence] => 4
            [Web Developer] => 6
        )
    
     )