Search code examples
phparraysmultidimensional-arraymergetranspose

How to merge arrays without overwriting its index in php?


I have this array

Array
(
[0] => Array
    (
        [0] => Name
        [1] => Email
        [2] => Address
    )

[1] => Array
    (
        [0] => vanson
        [1] => [email protected]
        [2] => gurgaon
    )

[2] => Array
    (
        [0] => john
        [1] => 
        [2] => 
    )

[3] => Array
    (
        [0] => sdf
        [1] => sdfsdf
        [2] => sdfsd
    )

)    

and i want this

Array
(       [0] => Name
        [1] => Email
        [2] => Address
        [0] => vanson
        [1] => [email protected]
        [2] => gurgaon
        [0] => john
        [1] => 
        [2] => 
        [0] => sdf
        [1] => sdfsdf
        [2] => sdfsd
  )    

WITHOUT OVERWRITING ITS INDEX

or i want to create dynamic arrays and put the same indexed values into individual arrays.something like this

$arr_1 = array(
                    [0] => Name
                    [1] => vanson
                    [2] => john
                    [3] => sdf
                    )
  $arr_2 = array(
                    [0] => Email
                    [1] => [email protected]
                    [2] => 
                    [3] => sdfsdf
                    )
   $arr_3 = array(
                    [0] => Address
                    [1] => gurgaon
                    [2] => 
                    [3] => sdfsd
                    )    

Arrays are created on the basis of the count of 1st indexed array.(Ex if 0th index has array of 4 then 4 arrays should be created.)


Solution

  • PHP arrays cannot have multiple values with the same index, so your first suggestion is not possible.

    However, the second option can be achieved with array_map(), by passing a null value as the callback parameter. Here's a convenient helper function that will do it (based on this excellent answer by Tadeck to another question):

    function array_transpose( $array ) {
        $array = array_merge( array( null ), array_values( $array ) );
        return call_user_func_array( 'array_map', $array );
    }
    
    $columns = array_transpose( $rows );
    

    (demo on codepad.org)