1

我有这个数组

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 个数组。)

4

2 回答 2

3

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

但是,第二个选项可以array_map()通过传递一个null值作为回调参数来实现。这是一个方便的辅助函数(基于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 );

codepad.org 上的演示

于 2012-12-29T05:27:48.023 回答
-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 ) ) ) 
于 2012-12-29T05:31:55.483 回答