Merging data in "type array" elements in an array, together in a new array
I think I blew you away by the title. But here's what I exactly need:
I have an array like this:
array(
'0' => array( 'the','data','i'),
'1' => array( 'need', 'is', 'this'),
'2' => array( 'complete', 'sentence')
);
which I want to become:
array(
'the','data','i','need','is','this','complete','sentence'
);
What's random:
- The number of elem开发者_如何学Goents in a child array element.
- The number of child array elements.
Since the problem you posed does not appear to be the general one of recursive flattening, it is probably worth giving the simple solution as an answer here, even though other SO questions address the general case.
All you need is
call_user_func_array("array_merge", $a);
To see it in a complete script:
<?php
$a = array(
array( 'the',' data', 'i' ),
array( 'need', 'is', 'this' ),
array( 'complete', 'sentence' )
);
echo var_dump($a);
echo "<br/><br/><br/>";
$b = call_user_func_array("array_merge", $a);
echo var_dump($b);
?>
This builds up the result by appending arrays and can be inefficient. You can check out SplFixedArray
which allows you to preallocate space. Then traverse the constituent arrays in your original array and load up the result. Here is a blog post that discusses SplFixedArray
and includes timing results: http://www.johnciacia.com/2011/02/01/array-vs-splfixedarray/
Here is a verbose version:
<?php
$a = array(
array( 'the','data','i'),
array( 'need', 'is', 'this'),
array( 'complete', 'sentence')
);
$size = 0;
foreach ($a as $subarray) {
$size += count($subarray);
}
$result = new SplFixedArray($size);
# If you do not have SPL, just use $result = Array(); and write to a high index first (probably)
$i = 0;
foreach ($a as $subarray) {
foreach ($subarray as $value) {
$result[$i++] = $value;
}
}
echo var_dump($result);
?>
精彩评论