如何更改下面多维数组的索引?

时间:2011-08-17 06:24:30

标签: php multidimensional-array

如何更改此波纹管数组

Array
(
    [0] => Array
    (
        [0] => Array
            (
                [0] => 35.2
            )

        [1] => Array
            (
                [0] => 49.5
            )            

    )

    [1] => Array
    (
        [0] => Array
            (
                [0] => 44
            )

        [1] => Array
            (
                [0] => 38.5
            )

    )
)

进入

Array
(
    [0] => Array
    (
        [0] => 35.2             

        [1] =>49.5                            

    )

   [1] => Array
    (
        [0] =>  44                

        [1] => 38.5                

    )

)

2 个答案:

答案 0 :(得分:2)

简单易用的方法是简单的嵌套foreach:

// be sure to include the &. Otherwise your edits will do nothing.
foreach( $input as &$level1 )
{
    // level 1 is the array of the arrays which contain your values
    // we need the keys and the arrays which hold the desired values
    foreach( $level1 as $key => $level2 )
    {
       // assign the key to be the value at 0 instead of its current value
       // (which happens to be level2)
       $level1[ $key ] = $level2[ 0 ];
    }
}

Sheepy建议在下面使用read_user_func_array来使用array_merge。这是一个好主意,我给了它一个+1。 (我鼓励其他人也这样做)。为了看哪个更好,我决定对两个解决方案进行基准测试:

结果:

 manual              0.074267864227295
 call_usr_func_array 0.13694596290588
 manual              0.080928087234497
 call_usr_func_array 0.13510608673096

然后我改变了测试顺序:

 call_usr_func_array 0.14956903457642
 manual              0.066309928894043
 call_usr_func_array 0.14821600914001
 manual              0.064701080322266

以下是基准代码:

$st = microtime(1);
$input = array();
for( $i = 0; $i < 10000; $i++ )
    $input[] = array( array( 1 ),array(  2 ),array(  3 ) );

// be sure to include the &. Otherwise your edits will do nothing.
foreach( $input as &$level1 )
{
    // level 1 is the array of the arrays which contain your values
    // we need the keys and the arrays which hold the desired values
    foreach( $level1 as $key => $level2 )
    {
       // assign the key to be the value at 0 instead of its current value
       // (which happens to be level2)
       $level1[ $key ] = $level2[ 0 ];
    }
}
print microtime(1) - $st;
print PHP_EOL;
$st = microtime(1);
$input = array();
for( $i = 0; $i < 10000; $i++ )
    $input[] = array( array( 1 ),array(  2 ),array(  3 ) );

foreach ( $input as $k => $ary ) {
  $input[$k] = call_user_func_array ( 'array_merge' , $ary );
}
print microtime(1) - $st;

答案 1 :(得分:1)

这是一个较短的版本。不过,它仍然是现实中的嵌套循环。

foreach ( $input as $k => $ary ) {
  $input[$k] = call_user_func_array ( array_merge , $ary );
}