How to change this bellow array
Array
(
[0] => Array
(
[0] => Array
(
[0] => 35.2
)
[1] => Array
(
[0] => 49.5
)
)
[1] => Array
(
[0] => Array
(
[0] => 44
)
开发者_JS百科 [1] => Array
(
[0] => 38.5
)
)
)
into
Array
(
[0] => Array
(
[0] => 35.2
[1] =>49.5
)
[1] => Array
(
[0] => 44
[1] => 38.5
)
)
The easy, easy way is a simple nested 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 proposed use of array_merge with call_user_func_array below. That is a good idea and I gave it a +1. (I encourage others to do the same). To see which was better, I decided to run a benchmark on both solutions:
The results:
manual 0.074267864227295
call_usr_func_array 0.13694596290588
manual 0.080928087234497
call_usr_func_array 0.13510608673096
I then reversed test order:
call_usr_func_array 0.14956903457642
manual 0.066309928894043
call_usr_func_array 0.14821600914001
manual 0.064701080322266
Here's the benchmark code:
$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;
Here is a shorter version. It is still a nested loop in reality, though.
foreach ( $input as $k => $ary ) {
$input[$k] = call_user_func_array ( array_merge , $ary );
}
精彩评论