Search code examples
phparraysmultidimensional-arraytransposemerging-data

Merge multiple flat arrays to form a 2d array with predefined column names


I have three arrays & i like to convert it in one multidimensional array.

$array1=array('Kathy', 'Adam', 'Jenny');
$array2=array('student','teacher','driver');
$array3=array(2, 5, 8);

$mix=array(); 
$mix['name']=array_values( $array1);
$mix['profession']=array_values( $array2);
$mix['SL']=array_values( $array3);

& from those arrays i can get below output:

Array
(
[name] => Array
    (
        [0] => Kathy
        [1] => Adam
        [2] => Jenny
    )

[profession] => Array
    (
        [0] => student
        [1] => teacher
        [2] => driver
    )

[SL] => Array
    (
        [0] => 2
        [1] => 5
        [2] => 8
    )

   )

Now i would like to get below output from above... anybody please help me how to do this ?

     [0]=>Array
      (
         [name] =>  Kathy
         [profession] =>student
         [SL] => 2
    )

    [1]=>Array
    (    
         [name] => Adam
         [profession] =>teacher
         [SL] =>  5
     )

    [2]=>Array
    (
         [name] => Jenny
         [profession] =>driver
         [SL] =>  8
    )

Solution

  • Use this:

      $array1=array('Kathy', 'Adam', 'Jenny');
      $array2=array('student','teacher','driver');
      $array3=array(2, 5, 8);
      $mix=array();
    
      for($i=0;$i<count($array1);$i++){
             $mix[$i]=array('name'=>$array1[$i],'profession'=>$array2[$i],'SL'=>$array3[$i]);
       }
    
      print_r($mix);
    

    Use this if all of array has same size.