如何改变下面的数组
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
)
)
最简单的方法就是嵌套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建议使用下面的array_merge和call_user_func_array。这是个好主意,我给了它+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;
下面是一个简短的版本。但它实际上仍然是一个嵌套循环。
foreach ( $input as $k => $ary ) {
$input[$k] = call_user_func_array ( array_merge , $ary );
}