如何合并数组而不覆盖其在php中的索引?

时间:2012-12-29 05:17:59

标签: php arrays multidimensional-array merge

我有这个数组

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

[1] => Array
    (
        [0] => vanson
        [1] => dhmax@pan.com
        [2] => gurgaon
    )

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

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

)    

我想要这个

Array
(       [0] => Name
        [1] => Email
        [2] => Address
        [0] => vanson
        [1] => dhmax@pan.com
        [2] => gurgaon
        [0] => john
        [1] => 
        [2] => 
        [0] => sdf
        [1] => sdfsdf
        [2] => sdfsd
  )    

没有覆盖其指数

或者我想创建动态数组并将相同的索引值放入单独的数组中。像这样

$arr_1 = array(
                    [0] => Name
                    [1] => vanson
                    [2] => john
                    [3] => sdf
                    )
  $arr_2 = array(
                    [0] => Email
                    [1] => dhmax@pan.com
                    [2] => 
                    [3] => sdfsdf
                    )
   $arr_3 = array(
                    [0] => Address
                    [1] => gurgaon
                    [2] => 
                    [3] => sdfsd
                    )    

根据第一个索引数组的计数创建数组。(例如,如果第0个索引的数组为4,则应创建4个数组。)

2 个答案:

答案 0 :(得分:3)

PHP arrays不能有多个具有相同索引的值,因此您的第一个建议是不可能的。

但是,通过传递null值作为回调参数,可以使用array_map()实现第二个选项。这是一个方便的辅助函数(基于this excellent answer by Tadeck到另一个问题):

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

答案 1 :(得分:-1)

PHP具有内置函数array_chunk(),您可以像这样使用它 -

$array = Array(Array(1=>'Name',2=>'Email'),Array(1=>'suresh',2=>'email@gmail.com'));        
echo "<pre>";print_r(array_chunk($array,1,true));
Output-
Array ( [0] => Array ( [0] => Array ( [1] => Name [2] => Email ) ) [1] => Array ( [1] => Array ( [1] => suresh [2] => email@gmail.com ) ) )